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

Using MEF in a VSTO project and a specific 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); 

everything works well, using different libraries, except when used in code

  ServiceLocator.Current.GetInstance<MyInterface>() 

which, of course, throws a NullReferenceException

Given that the ServiceLocator is in its own DLL, I wonder how to connect it or even possible?

+4
source share
1 answer

Well, you can try this where you define your container:

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

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

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

+3
source

Source: https://habr.com/ru/post/1435723/


All Articles