2012-01-10 95 views
3

在我App.xaml.cs我有如何初始化MEF ServiceLocator.Current?

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为空。

如何让它工作?

回答

1

我认为你错过了拨打ComposePartsCompose设置CompositionContainer的电话。在开始通过GetInstance解决实例之前。

还有一个MSDN walk through here,和一些其他样品herehere。相关的代码片段:

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 
+1

似乎没有这样的工作。 ComposeParts在Silverlight中不可用 – katit 2012-01-10 17:40:04

+0

@katit在SL中有'Compose'?如果可能有帮助,我会用这种方法修改答案。 – 2012-01-10 21:44:21

1

我有同样的问题..

,发现这可能是有益的,

http://www.itwox.com/post/Using-MEF-with-Common-Service-Locator.aspx

关键语句是

服务定位.SetLocatorProvider(()=> whateveryourlocatorinstanceis);

+1

链接已损坏。 – 2012-11-14 12:26:58

+0

Wayback机器是你的朋友:https://web.archive.org/web/20120125090930/http://www.itwox.com/post/Using-MEF-with-Common-Service-Locator.aspx – 2018-02-23 19:05:23