Wednesday, November 02, 2011

C#–Loading dlls at runtime and finding classes that implement an interface

Given: An interface that you have defined:

public interface IMyPluginInterface
{
    int GetInteger();
}

When: Your application runs

Then: It should load dlls at run time and call GetInteger on all those classes that implement the interface IMyPluginInterface

Solution: Here is how you can do that:

static void Main(string[] args)
{
    //find some dlls at runtime
    string[] dlls = Directory.GetFiles(Environment.CurrentDirectory, "MyPlugin*.dll");

    //loop through the found dlls and load them
    foreach (string dll in dlls)
    {
        System.Reflection.Assembly plugin = System.Reflection.Assembly.LoadFile(dll);
       
        //now find the classes that implement the interface IMyPluginInterface and get an object of that type
        var instances = from t in plugin.GetTypes()
                        where t.GetInterfaces().Contains(typeof(IMyPluginInterface))
                                 && t.GetConstructor(Type.EmptyTypes) != null
                        select Activator.CreateInstance(t) as IMyPluginInterface;

        //now call the GetInteger method defined by the interface
        foreach (var instance in instances)
        {
            Console.WriteLine(instance.GetInteger());
        }

    }

    Console.ReadLine();
}

public class MyPlugin1 : IMyPluginInterface
{
    public int GetInteger()
    {
        return 1;
    }
}

No comments: