how to use MEF do DI(DEPENDENCY INJECTION )

MEF Demo

1.Create one interface project ,named IMEFTestCommon

Add interface code

public interface IPrintf
    {
       void Print();
    }


2.Create one implement project,named MEFImplement

Add System.ComponentModel.Composition.dll

Add 2 classes, one is:

[Export(typeof(IPrintf))]
    public class PrintPlus : IPrintf
    {
       public void Print()
        {
           Console.WriteLine("+++++");
        }
    }
 


Another one :

public class PrintStar : IPrintf
    {
       public void Print()
        {
           Console.WriteLine("****");
        }
    }


3.Create one Console ApplicationProject , named MEFTest

Addone Class MEFHelper :

 public class MefHelper
    {
    [Import(typeof(IPrintf))]
    private IPrintf _print;
    	public void LoadAssembly()
    	{
	var aggregateCatalog = new AggregateCatalog();    
	 var directoryName =Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
	if (directoryName != null)
 	{
	var directoryPath = “E:\MEFTest\ExportComponents”;
	var directoryCatalog= new DirectoryCatalog(directoryPath, "*.dll");             
 	aggregateCatalog.Catalogs.Add(directoryCatalog);
	}
	var container = new CompositionContainer(aggregateCatalog);
	container.ComposeParts(this);
    	}
	public void Load2()
	{
	var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
	var container = new CompositionContainer(catalog);
	container.ComposeParts(this,new PrintStar(),new PrintPlus());
	}
	public void Execute()
	{
	_print.Print();
	}
}




TheProjects :

In Program , Add Code :

 private static MefHelper _mefHelper;
       static void Main(string[] args)
        {
           _mefHelper = new MefHelper();
           _mefHelper.LoadAssembly();
           _mefHelper.Execute();
           Console.Read();
        }

finished .

When you change the Export class , can change the behavior dynamic.

Now the export class is :

Then the result is like this :

Then I change the export class to another one :

Then the result islike this :

Note :

1. two load assembly method must be executed before invoke the interface .

2.

The first one is setting the directory (MEF will always find the*.dll under the bin folder ,if it find the match one ,will execute ,then find the folders you passed in),

second one is pass the objects to compose .normally , first one should be the class object that include the interface member(in this example is MEFHelper.cs) , and have [import] attribute ,others can be the classes that implement the interface and have [export] attribute accordingly (PrintStar.cs , PrintPlus.cs).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值