Search code examples
c#.netprismmefservice-locator

How to resolve ServiceLocator.Current is null using VSTO and MEF


Using MEF in a VSTO project and defined container as follows

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

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

all's working well using various libraries except where the code uses

 ServiceLocator.Current.GetInstance<MyInterface>()

which ofcourse throws a NullReferenceException

Considering ServiceLocator is in it's own dll, wondering how to wire it up or is it even possible ?


Solution

  • Ok, you could try this, where you define your container:

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

    The MefServiceLocatorAdapter is in the Microsoft.Practices.Prism.MefExtensions namespace.

    **EDIT:
    But remember that using ServiceLocator is considered an anti-pattern, and defeats the purpose of IoC/DI.