在我的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为null。
我如何使其起作用?
[我认为您在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
我有同样的问题..
并发现这可能有所帮助,
http://www.itwox.com/post/Using-MEF-with-Common-Service-Locator.aspx
主要说明是
ServiceLocator.SetLocatorProvider(()=>随便你的位置实例是);