[英]The way to create a plug-in application
I have a .NET WinForm application. 我有一个.NET WinForm应用程序。 I want when my application run, it will detect a DLL.
我希望当我的应用程序运行时,它会检测到一个DLL。 If this DLL exists, my app will load and use it like a built-in DLL.
如果此DLL存在,我的应用程序将加载并使用它像内置DLL。
Please help me some examples. 请帮我举几个例子。 Thanks.
谢谢。
Read up on MEF - Microsoft Extensibility Framework, in the System.ComponentModel.Composition namespace. 阅读System.ComponentModel.Composition命名空间中的MEF - Microsoft Extensibility Framework。 Part of the core .NET 4.0 functionality.
.NET 4.0核心功能的一部分。
You can also use the Microsoft Add-In Framework (MAF) using System.Addin Namespace. 您还可以使用System.Addin命名空间使用Microsoft加载项框架(MAF)。
Read more on http://msdn.microsoft.com/en-us/library/bb384200.aspx 有关详细信息,请访问http://msdn.microsoft.com/en-us/library/bb384200.aspx
If it's just one DLL, add a reference to it and catch any exceptions using it. 如果它只是一个DLL,添加对它的引用并使用它捕获任何异常。 If there can be many (maybe 3rd party) DLL, use one of the
Assembly.Load*
methods and you can then enumerate classes from the Assembly object. 如果可能有许多(可能是第三方)DLL,请使用
Assembly.Load*
方法之一,然后您可以枚举Assembly对象中的类。
See some examples in my BuilderPro project, specifically Extensions.cs and Extension.cs . 请参阅我的BuilderPro项目中的一些示例,特别是Extensions.cs和Extension.cs 。
If you are looking for something simple using reflection, you could take the approach of loading the type information from the config file: 如果您正在寻找使用反射的简单方法,您可以采用从配置文件加载类型信息的方法:
public interface IMyPlugin
{
void DoSomethingPlugInIsh();
}
class Program
{
static void Main(string[] args)
{
IMyPlugin plugin1 = CreateFromConfig<IMyPlugin>("PluginType");
plugin1.DoSomethingPlugInIsh();
// etc...
}
static T CreateFromConfig<T>(string typeSettingName)
where T : class
{
string typeName = ConfigurationManager.AppSettings[typeSettingName];
if (string.IsNullOrEmpty(typeName))
return null;
var type = Type.GetType(typeName);
return (T)Activator.CreateInstance(type);
}
}
The config file would contain the information about the type you are going to instantiate, so people could change it to their own plugin: 配置文件将包含有关您要实例化的类型的信息,因此人们可以将其更改为自己的插件:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="PluginType" value="TestPlugin.MyClass, TestPlugin, Version=1.0.0.0, Culture=neutral" />
</appSettings>
</configuration>
And the class would reference your interface and implement it: 该类将引用您的接口并实现它:
public class MyClass : IMyPlugin
{
public void DoSomethingPlugInIsh()
{
Console.WriteLine("Hello there");
}
}
Hope that helps, 希望有所帮助,
John 约翰
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.