问题
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