annantDev
annantDev

Reputation: 367

Instantiating a class dynamically c#

I am working on developing a plug and play framework in ASP.Net MVC whereby I can define modules as separate projects from the Main project. So, a developer can create as many modules as they want.

What I need is that to be able to update settings of any of such modules. For that, in the main project, I defined a base class for some common settings plus each module has its own custom settings. When there is any edit on a module, I have to instantiate instance of that module in the main project. But, main project has no knowledge of any modules.

How do I achieve this?

Thanks!

Upvotes: 1

Views: 315

Answers (2)

Oblivion2000
Oblivion2000

Reputation: 616

Depending on your need, you would have to create a solution that relies on interfaces.

Essentially, the application exposes an API dll with an interface called IModule. IModule has one method called Run(). Your main application will load up the module's assembly, look for something that implements IModule, makes one of those objects and calls Run() on it.

Here is an old article describing how to host a sandbox to run modules inside. http://msdn.microsoft.com/en-us/magazine/cc163701.aspx

namespace MyApplication.Api 
{
    public interface IModule
    { 
       void Run();
    }
}

The developer would create something like this

public class MyObject : MarshalByRefObject, IModule
{
    public void Run()
    {
        // do something here    
    }
}

The application will load it up with some kind of Reflection.

public void LoadModule()
{
     var asm = System.Reflection.Assembly.Load(/* Get the developer module name from somewhere*/);
     var types = asm.GetExportedTypes();
     foreach(var t in types)
     {
         foreach(var i = t.GetInterfaces())
         {
             if(i == typeof(IModule))
             {
                 var iModule = System.Activator.CreateInstance(t);
                 iModule.Run();
             }
         }
     }
}

It would be best if you run the code in another appDomain, but it adds a lot of complexity.

public void LoadModuleInAppDomain()
{
    // Spin up a new AppDomain

    // Load the assembly into the app domain

    // Get the object

    // Call the Run Method

}

Upvotes: 1

DarthVader
DarthVader

Reputation: 55032

You can use dependency injection and inject those modules to your application at composition root. As per configuration you can use code or xml (configuration file). You can do auto wiring, late binding etc depending on what you really need.

You can also have initializers at each module so whenever you register a module, it should initialize your registered modules and inject dependencies etc.

Upvotes: 1

Related Questions