Hosting MEF in an application is actually very simple, simply by creating an instance of a composite container object (Compositioncontainer), and then adding the part (Parts) that needs to be combined and the current host program to the container. First you need to add a reference to the MEF framework, both System.ComponentModel.Composition.dll and in detail the following code block:
private void Compose()
{
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
The implementation of the MEF can be accomplished through the above code, and is actually not so simple in the development process of using MEF. It is possible to define one or more import and export parts and then combine them through the MEF container, which can actually be understood as an implementation of dependency injection. For example, define a library interface and an implementation class for an interface, on the basis of which the MEF's import export features are used:
public interface IBookService
{
void GetBookName();
}
/// <summary>
/// 导入
/// </summary>
[Export(typeof(IBookService))]
public class ComputerBookService : IBookService
{
public void GetBookName()
{
Console.WriteLine("《Hello Silverlight》");
}
}
The above code, by using MEF's [System.ComponentModel.Composition.Export] to export the implementation of the interface, allows the implementation of the interface to exist as a container part, and then assemble the load through a composite container. In this process, the process of instantiating an interface is included. Next, you need to define an interface's properties in the MEF host program and annotate it with the [System.ComponentModel.Composition.Import] attribute to implement the import of the interface implementation class. The following code block:
/// <summary>
/// 导入接口的实现部件 (Part)
/// </summary>
[Import]
public IBookService Service { get; set; }
Completion of the import and export of the interface and implementation of the development and characteristics of the configuration, the rest of the following is a combination of the parts and the host program itself is added to the composite container to implement import (imports) and exports (export) assembly.
/// <summary>
/// 宿主MEF并组合部件
/// </summary>
private void Compose()
{
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
//将部件(part)和宿主程序添加到组合容器
container.ComposeParts(this,new ComputerBookService());
}