Search code examples
c#namespacesdynamic-code

Execute a method of a different namspace by dynamic code in C# winforms


I am implementing a dynamic code execution in C# which allows users to write their own c# for that particular application.

I am using C# code compiler for executing the dynamic codes. The C# compiler reads the code file and construct the code in new namespace (a complete new code), compiles and runs it. In other view the base application host all these.

I have few methods that are present in host application that I want to be executed by the dynamic code. Is there any way by which the method of other namespace or application can be executed?


Solution

  • Could you force the author of your script to implement an interface, or you could even wrap their code with your own implementation..

    Something like

    public interface IMyApplication
    {
          void DoSomethingInMyMainApp();
    }
    public interface IScriptKiddie
    {
          void Init(IMyApplication app);
    }
    

    Then your l33t scripters can write

    public class MyScript : IScriptKiddie //< you could emit this yourself
    {
    
         public void Init(IMyApplication app) //<could emit this yourself if scripter knows app keyword
         {
              app.DoSomethingInMyMainApp();
         }
    }
    

    and in your app you can provide a concrete implementation of IMyApplication to pass into the class when you have compiled, constructed the class then pass into Init method.