如何初始化MEF ServiceLocator.Current?

问题描述 投票:3回答:2

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

我如何使其起作用?

c# silverlight mef
2个回答
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

2
投票

我有同样的问题..

并发现这可能有所帮助,

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

主要说明是

ServiceLocator.SetLocatorProvider(()=>随便你的位置实例是);

© www.soinside.com 2019 - 2024. All rights reserved.