Instantiating classes that implement an interface e.g. plugin activation

suggest change

If you want your application to support a plug-in system, for example to load plug-ins from assemblies located in plugins folder:

interface IPlugin
{
    string PluginDescription { get; }
    void DoWork();
}

This class would be located in a separate dll

class HelloPlugin : IPlugin
{
    public string PluginDescription => "A plugin that says Hello";
    public void DoWork()
    {
        Console.WriteLine("Hello");
    }
}

Your application’s plugin loader would find the dll files, get all types in those assemblies that implement IPlugin, and create instances of those.

public IEnumerable<IPlugin> InstantiatePlugins(string directory)
{
    var pluginAssemblyNames = Directory.GetFiles(directory, "*.addin.dll").Select(name => new FileInfo(name).FullName).ToArray();
    //load the assemblies into the current AppDomain, so we can instantiate the types later
    foreach (var fileName in pluginAssemblyNames)
        AppDomain.CurrentDomain.Load(File.ReadAllBytes(fileName));
    var assemblies = pluginAssemblyNames.Select(System.Reflection.Assembly.LoadFile);
    var typesInAssembly = assemblies.SelectMany(asm => asm.GetTypes());
    var pluginTypes = typesInAssembly.Where(type => typeof (IPlugin).IsAssignableFrom(type));
    return pluginTypes.Select(Activator.CreateInstance).Cast<IPlugin>(); 
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Reflection:
* Instantiating classes that implement an interface e.g. plugin activation

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
61 Reflection
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script