Registering new types with MEF container from ViewModel

Topics: Prism v4 - WPF 4
Feb 14, 2012 at 11:08 AM

Hi There,

In my LoginViewModel, the method to login returns on successful login a IUser which I would like to register with my MEF container so that it can be injected into other viewmodels created. How should I do this?

Feb 14, 2012 at 2:28 PM
Edited Feb 14, 2012 at 2:30 PM

Hi James,

I believe you might find the following thread useful, where a similar concern is addressed:

I hope you find this handy,

Agustin Adami

Feb 15, 2012 at 9:34 AM

Ahhh I see so this enables me to access the container. How exactly would I register the container in the ConfigureContainer method?

Feb 15, 2012 at 12:35 PM

Hi James,

I suggested the aforementioned thread as I believe this could be a possible way to register an instance dynamically when using MEF. You will still need to create and configure the container in your Bootstrapper when initializing your application as usual. There you will also have the option to create an instance of a class and register that particular instance with the container, by overriding the ConfigureContainer method, and also using the ComposeExportedValue method, like in the following code snippet:

protected override void ConfigureContainer()





For more information about this you can check the section Registering Types With MEF of Chapter 3: Managing Dependencies Between Components of the Prism documentation at MSDN.


Agustin Adami

Feb 15, 2012 at 1:02 PM

I understand I have my bootstrapper as it was etc. I thought the solution was to register the Composition Container so I could access it via the ServiceLocator later in my ViewModel? Then I could compose the type when I have the required data to.

Therefore I wanted to know how to register the Composition Container in this ConfigureContainer method.

So in my viewmodel I can do this:

var container = ServiceLocator.Current.GetInstance(CompositionContainer);

and then compose my component. I was just confused with how to do the 
"register the Composition Container, by overriding the ConfigureContainer’s method in the Boostrapper" part.
Feb 20, 2012 at 8:51 AM

Any help with this?

Feb 24, 2012 at 5:07 PM

Hi James,

Based on my understanding, you can register the current CompositionContainer instance in the ConfigureContainer method of your bootstrapper doing, for example, something like this:

protected override void ConfigureContainer()

    // Registers the current composition container.

Then, you can resolve the CompositionContainer through the ServiceLocator as you mentioned, or inject it as a dependency in the constructor of your view model:

public MyViewModel(CompositionContainer container)

I hope you find this useful,

Damian Cherubini

Mar 2, 2012 at 8:35 AM

Yep sorted thank you