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).