决定在运行时调用哪个dll
本文关键字:dll 调用 运行时 决定 | 更新日期: 2023-09-27 18:11:23
我使用Process.Start()
方法根据需要启动特定的可执行文件。可执行文件是量身定制的,有很多这样的文件,路径&名字和他们所做的工作一起在数据库中。
如果它们都实现了一个接口,有没有其他方法可以在进程中启动它们?我希望能够调试它们,并在调用它们时具有更好的类型安全性。
我可以在每个解决方案中设置一个库项目,然后实例化该库并让它代替可执行文件完成工作。这个问题是关于一种机制,允许我根据接口进行构建,然后在运行时按其名称加载库。
如果需要自定义解决方案,可以使用如下内容。否则,你可以使用在Prism中使用Unity或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();
}