Unbound C # class reference

This may be a strange question.

I need to belatedly link an uncompiled C # class (.cs). Not even sure if this is possible. The class will not be part of the project or reference. The only thing I will know about is the location of the file.

The file will not be compiled at runtime as it will be part of the app_code website. Just just create an instance and then call the function on it.

Is it possible?

Thank you in advance

+2


source to share


3 answers


It sounds like you want to compile and reference your class at runtime. This is definitely possible.

This article should point you in the right direction ... http://support.microsoft.com/kb/304655



Be aware that once you load an assembly into memory, you cannot unload it unless you unload the entire application domain. Therefore, if you need to unload code, you will have to load it into a new AppDomain.

+1


source


You didn't ask about compilation, so I assume you just want to instantiate the class and use it.

You must make the class implement an interface that covers the functionality you need, and then you can instantiate it using the Activator class :



ObjectHandle fooHandle = Activator.CreateInstanceFrom(
   @"C:\somePath\FooAssembly.dll", "FooNamespace.Foo");
IFoo foo = (IFoo)fooHandle.Unwrap();

      

The class must have a default constructor. When loading assemblies by name as above, consider security implications.

+1


source


You can use the CodeProvider classes

CodeDomProvider cdp = Microsoft.CSharp.CSharpCodeProvider.CreateProvider("CSharp");
CompilerResults cr = cdp.CompileAssemblyFromFile(<CompilerParameters>,<string [] of files to compiler>);

      

just replace the appropriate object for you and with a string array of the actual filenames.

you can also load the code into line and compile directly from there

The resulting assembly can be found at

cr.CompiledAssembly

      

0


source







All Articles