4

在 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 中,想知道如何连接它,或者它甚至可能吗?

4

1 回答 1

3

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

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

MefServiceLocatorAdapter 位于 Microsoft.Practices.Prism.MefExtensions 命名空间中。

**编辑:
但请记住,使用 ServiceLocator 被认为是一种反模式,并且违背了 IoC/DI 的目的。

于 2012-09-28T15:41:01.143 回答