2012-09-23 35 views
4

在VSTO项目中使用MEF和定义容器如下如何解决ServiceLocator.Current为null使用VSTO和MEF

 var catalog = new AggregateCatalog(); 
     catalog.Catalogs.Add(new AssemblyCatalog(this.GetType().Assembly)); 
     catalog.Catalogs.Add(...); 

     container = new CompositionContainer(catalog); 
     container.SatisfyImportsOnce(this); 

所有的工作以及使用,除非该代码使用

ServiceLocator.Current.GetInstance<MyInterface>() 
各个库

哪个课程引发NullReferenceException

考虑到ServiceLocator是在它自己的dll中,想知道如何连接它或甚至有可能吗?

回答

3

好吧,你可以试试这个,你定义你的容器:

var mefAdapter = new MefServiceLocatorAdapter(container); 
ServiceLocator.SetLocatorProvider(() => mefAdapter); 

的MefServiceLocatorAdapter是在Microsoft.Practices.Prism.MefExtensions命名空间。

** 编辑:
但请记住,使用服务定位被认为是一个反模式,并且击败的IoC/DI的目的。