Dynamically loading classes (with custom behavior) from different assemblies?

后端 未结 6 993
遥遥无期
遥遥无期 2021-02-10 14:36

We are building an app for few customers, each has its own requirements along with the similar ones. We also want to keep all the code in the same app, not branch it, and the IF

6条回答
  •  孤独总比滥情好
    2021-02-10 15:31

    This is how I load plug-ins (add-ins) into one of my projects:

    const string PluginTypeName = "MyCompany.MyProject.Contracts.IMyPlugin";
    
    /// Loads all plugins from a DLL file.
    /// The filename of a DLL, e.g. "C:\Prog\MyApp\MyPlugIn.dll"
    /// A list of plugin objects.
    /// One DLL can contain several types which implement `IMyPlugin`.
    public List LoadPluginsFromFile(string fileName)
    {
        Assembly asm;
        IMyPlugin plugin;
        List plugins;
        Type tInterface;
    
        plugins = new List();
        asm = Assembly.LoadFrom(fileName);
        foreach (Type t in asm.GetExportedTypes()) {
            tInterface = t.GetInterface(PluginTypeName);
            if (tInterface != null && (t.Attributes & TypeAttributes.Abstract) !=
                TypeAttributes.Abstract) {
    
                plugin = (IMyPlugin)Activator.CreateInstance(t);
                plugins.Add(plugin);
            }
        }
        return plugins;
    }
    

    I assume that each plug-in implements IMyPlugin. You can define this interface any way you want. If you loop through all DLLs contained in a plug-ins folder and call this method, you can automatically load all the available plug-ins.

    Usually you would have at least three assemblies: One containing the interface definition, the main assembly referencing this interface assembly and at least one assembly implementing (and of course referencing) this interface.

提交回复
热议问题