C # ICodeCompiler - starting a class

I just opened the .NET ICodeCompiler (keep in mind that I don’t know anything about this, except that it can run programs inside the program). How will I write the scripting architecture around this?

Ideally, I would like the user to write code that is derived from the interface. This interface will be defined by me in my program (it cannot be edited by the user). The user would execute it, and CompileEngine would launch it. My program will then call the various methods that they have implemented. Is it possible?

eg. They would have to implement this:

public interface IFoo { void DoSomething(); } 

Then I compiled their implementation and instantiated my object:

 // Inside my binary IFoo pFooImpl = CUserFoo; pFooImpl.DoSomething(); 
+4
source share
2 answers

What you want to achieve is possible, but BEWARE !! Each time you compile code, it compiles as an assembly and is loaded into memory. If you change the "script" code and recompile it, it will be loaded again as another assembly. This can cause a “memory leak” (although this is not a real leak), and there is no way to unload these unused assemblies.

The only solution is to create another AppDomain and load this assembly into this AppDomain, and then unload if the code changes and do it again. But it’s harder to do.

UPDATE

For compilation, see here: http://support.microsoft.com/kb/304655

Then you will need to load the assembly using Assembly.LoadFrom .

  // assuming the assembly has only ONE class // implementing the interface and method is void private static void CallDoSomething(string assemblyPath, Type interfaceType, string methodName, object[] parameters) { Assembly assembly = Assembly.LoadFrom(assemblyPath); Type t = assembly.GetTypes().Where(x=>x.GetInterfaces().Count(y=>y==interfaceType)>0).FirstOrDefault(); if (t == null) { throw new ApplicationException("No type implements this interface"); } MethodInfo mi = t.GetMethods().Where(x => x.Name == methodName).FirstOrDefault(); if (mi == null) { throw new ApplicationException("No such method"); } mi.Invoke(Activator.CreateInstance(t), parameters); } 
+2
source

If I understand correctly what you want to do, I think CodeDom and this article can help you. Is this what you are looking for?

+1
source

All Articles