Decide what dll to call at runtime

雨燕双飞 提交于 2019-12-12 04:09:32

问题


I am using the Process.Start() method to launch a specific executable as needed. The executable is tailor-made, there are many of these, and the paths & names are in the database together with the job they do.

Is there another way to launch them in-process, if they all implement an interface? I want to be able to debug them and have better type safety when calling them.

I can set a library project in each solution, then instantiate that library and have it do the job instead of the executable. The question is about a mechanism that would allow me to build against the interface then load the library by its name at runtime.


回答1:


You can use something like the following if you want custom solution. Otherwise, you can use modular patterns implemented in Prism with Unity or MEF.

public interface IPlugin
{
    void Start();
}

// You can change this to support loading based on dll file name
// Use one of the other available Assembly load options
public void Load(string fullAssemblyName)
{
    var assembly = System.Reflection.Assembly.Load(fullAssemblyName);

    // Assuming only one class implements IPlugin 
    var pluginType = assembly.GetTypes()
               .FirstOrDefault(t => t.GetInterfaces()
               .Any(i=> i == typeof(IPlugin)));

    // Concrete class implementing IPlugin must have default empty constructor
    // for following instance creation to work
    var plugin = Activator.CreateInstance(pluginType) as IPlugin;
    plugin.Start();
}


来源:https://stackoverflow.com/questions/24557849/decide-what-dll-to-call-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!