[Silverlight入门系列]Prism的MEF依赖注入单例(Singleton)的Service
时间:2011-04-29 来源:Mainz
MEF的默认Export和Import的共享属性是单例模式/Singleton的(即一个container下面最多一个实例),如果设置为[PartCreationPolicy(CreationPolicy.NonShared)]则每个调用者创建一个实例。具体见:
- Shared: the part author is telling MEF that at most one instance of the part may exist per container.
- NonShared: the part author is telling MEF that each request for exports of the part will be served by a new instance of it.
- Any or not supplied value: the part author allows the part to be used as either “Shared” or “NonShared”.
代码示例:Service Export
[Export(typeof(IMarketFeedService))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class MarketFeedService : IMarketFeedService, IDisposable
{
//....
}
Service引用: Import
[Import]
public IMarketFeedService TheMarketFeedService{ private get; set; }
//Public是MEF要求的
此外,由于MEF是可以Composite的,也就是说Export的一个对象里面也可以Import别的对象,是一个组合(composite)的关系。所以这里面情况比较复杂,具体请查看这个《有关MEF共享策略的文章》。更多有关MEF的使用方法指导看这个文章。
相关阅读 更多 +