在我的App.xaml.cs中我有
private void InitializeContainer()
{
var catalogs = new AggregateCatalog();
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
catalogs.Catalogs.Add(catalog);
// Also adding Interactions project
catalog = new AssemblyCatalog(typeof(InteractionsService).Assembly);
catalogs.Catalogs.Add(catalog);
// initialize the main application composition host (container)
CompositionHost.Initialize(catalogs);
}
但是,当我尝试将对象初始化为如下所示的行时:
this.InteractionsService = ServiceLocator.Current.GetInstance<IInteractionsService>();
我得到的异常是我的ServiceLocator.Current为空。
如何让它发挥作用?
答案 0 :(得分:2)
我有同样的问题..
并发现这可能会有所帮助,
http://www.itwox.com/post/Using-MEF-with-Common-Service-Locator.aspx
关键陈述是
ServiceLocator.SetLocatorProvider(()=&gt; whateveryourlocatorinstanceis);
答案 1 :(得分:1)
我认为您在设置ComposeParts
时错过了对Compose
或CompositionContainer
的调用。在您开始通过GetInstance
解析实例之前。
有一个MSDN walk through here,还有一些其他样本here和here。相关的代码段:
private CompositionContainer _container
//your code
var batch = new CompositionBatch();
batch.AddPart(this);
_container.Compose(batch);
//or more simply
_container.ComposeParts(this) //if this method is supported