Как инициализировать MEF ServiceLocator.Current? - PullRequest
3 голосов
/ 10 января 2012

В моем 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 ]

2 голосов
/ 25 апреля 2012

У меня был тот же вопрос ..

и нашел это полезным,

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

ключевое утверждение:

ServiceLocator.SetLocatorProvider (() => whateveryourlocatorinstanceis);

1 голос
/ 10 января 2012

Я думаю, что вы пропускаете вызов ComposeParts или Compose в настройке CompositionContainer.Прежде чем вы начнете разрешать экземпляры с помощью GetInstance.

Здесь будет проходить MSDN и некоторые другие примеры здесь и здесь .Соответствующий фрагмент кода:

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
...