C# MEF使用1(不修改代码,挂载不同dll)
MEF是4.0的新特性 ,建立项目 请用4.0以上框架
1、新建 一个 类库项目 名为Itest,删除其中Class1.cs 添加 一个接口文件,命名为 ItestService
namespace ITest
{
public interface ITestService
{
void test();
}
}
2、然后 建立控制台项目(主项目) 名为MEFTest项目 项目中添加引用 Itest与 System.ComponentModel.Composition.dll
在Program.cs 中写
class Program
{
[Import(typeof(ITest.ITestService))] //声明要导入 特定类的 接口
private ITest.ITestService tt;
static void Main(string[] args)
{
Program p = new Program();
p.tt.test();
Console.ReadKey();
}
public Program()//构造函数 中 代码 主要作用 加载Test.dll文件中的类
{
var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "Test.dll");
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
3、建立一个类库项目 名为:Test1,添加引用 Itest与 System.ComponentModel.Composition.dll 编写代码如下:
[Export(typeof(ITest.ITestService))] //导出类型
public class Class1:ITest.ITestService
{
public void test()
{
Console.WriteLine("Test.dll Test1测试");
Console.ReadKey();
}
}
编译次项目 去debug下 拿到 test.dll 然后,把这个 dll 放到 主项目 bebug 下就可以了

浙公网安备 33010602011771号