如何初始化MEF ServiceLocator.Current?

时间:2012-01-10 03:33:59

标签: c# silverlight mef

在我的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为空。

如何让它发挥作用?

2 个答案:

答案 0 :(得分:2)

我有同样的问题..

并发现这可能会有所帮助,

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

关键陈述是

ServiceLocator.SetLocatorProvider(()=&gt; whateveryourlocatorinstanceis);

答案 1 :(得分:1)

我认为您在设置ComposeParts时错过了对ComposeCompositionContainer的调用。在您开始通过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