Each of the exported parts that can be dynamically assembled in the MEF is lifecycle-the lifecycle is generally not managed without special requirements, and in fact MEF has the default lifecycle management for each component, and the MEF's lifecycle is divided into three categories: any, Shared and nonshared are defined in the System.ComponentModel.Composition.CreationPolicy enumeration object.
namespace System.ComponentModel.Composition
{
public enum CreationPolicy
{
Any = 0,
Shared = 1,
NonShared = 2,
}
}
Any representation that can be shared or unshared, where instances of a part are automatically controlled according to different request requirements using the MEF container; shared represents a shared part, and a plug-in part that is of the same type can be used in multiple MEF combination containers, followed by the nonshared type, which indicates that the part instance is not shared. A new object instance is created whenever a new request is made. In MEF, the life cycle configuration of a part is implemented through the Partcreationpolicyattribute attribute.
public interface IBookService
{
string GetBookName();
}
[PartCreationPolicy(CreationPolicy.Any)]
[Export(typeof(IBookService))]
public class MEFBookService : IBookService
{
public string GetBookName()
{
return "《MEF程序设计指南》";
}
}
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IBookService))]
public class ASPNETBookService : IBookService
{
public string GetBookName()
{
return "《ASP.NET项目案例》";
}
}
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IBookService))]
public class SLBookService : IBookService
{
public string GetBookName()
{
return "《Silverlight高级编程》";
}
}