利用反射方式实现插件模型,wpf控件作为插件,然后用另外的窗体加载。
首先定义插件接口:
public interface IUserControlLevel1
{
string PluginName { get; set; }
int PluginIndex { get; set; }
}
userControl继承定义的接口:
/// <summary>
/// UserControl1.xaml 的交互逻辑
/// </summary>
public partial class UserControl1 : UserControl, IUserControlLevel1
{
public UserControl1()
{
InitializeComponent();
}
public string PluginName
{
get;
set;
}
public int PluginIndex
{
get;
set;
}
}
管理类里定义寻找插件,并返回结果。
主要代码如下:
public static List<IUserControlLevel1> GetUserControlLevel1(string directoryPath)
{
List<IUserControlLevel1> li = new List<IUserControlLevel1>();
string[] files = Directory.GetFiles(directoryPath, "*.dll");
foreach (var file in files)
{
Assembly assembly = Assembly.LoadFrom(file);//加载控件
Type[] types = assembly.GetTypes();//加载所有类型
foreach (var type in types)
{
if (!type.IsClass || type.IsNotPublic)
{
continue;
}
Type[] interfaces = type.GetInterfaces();//加载该类型接口
if (interfaces.Contains(typeof(IUserControlLevel1)))
{
object obj = Activator.CreateInstance(type);
IUserControlLevel1 uc = (IUserControlLevel1)obj;
Object obj2 = type.InvokeMember(type.FullName,
BindingFlags.CreateInstance, null, null, null);
IUserControlLevel1 uc2 = (IUserControlLevel1)obj2;
li.Add(uc2);
continue;
}
}
}
return li;
}
然后主窗体可以寻找默认路径下的插件 并加载到界面。
源码下载地址如下:
http://files.cnblogs.com/files/lizhijian/%E6%8F%92%E4%BB%B6%E6%A8%A1%E5%9E%8B.rar
感谢每一位阅读此篇文章的人,希望可以帮到你。