PartCreationPolicy.Shared

Aug 20, 2010 at 11:04 AM

I am having a problem with MEF instantiating a part multiple time, when the part is attributed with PartCreationPolicy.Shared.

Are there any 'gotchas' that I should be aware of?

The part in question is the ApplicationModel - something that should act as a singleton model for the whole application. Numerous view models throughout the application have this injected into them via their constructors. However, on start-up of the application I have noticed that its constructor is being called twice. 

Basically, the first instance of the 'Model' is created by my root application view model, via constructor injection. The next instance is created by a child View's view model, also via constructor injection.

All further 'requests' for the model, which are also via constructor injection, are given the original instance of the model. So it is only this one view model that is getting injected with a new instance.

At no point do I manually instantiate an instance of the model.

Any ideas?

Thanks

Mark

 

Aug 20, 2010 at 11:38 AM

Its also probably worth pointing out, as I suspect that this may be where the problem lies although I don't know why, that I am using CompositionInitializer.SatisfyImports on the child view in order to inject (property injection) its View Model. And it is this ViewModel that is getting a different instance of the supposedly Shared part.

Does CompositionInitializer.SatisfyImports use the same container, or does it create a brand new one? I create my Container in the MEFBootstrapper supplied by Prism 4.

Aug 20, 2010 at 3:42 PM
mcampster wrote:

Does CompositionInitializer.SatisfyImports use the same container, or does it create a brand new one? I create my Container in the MEFBootstrapper supplied by Prism 4.

It uses its own default container loaded with all parts in the XAP, unless you initialize it by passing your own container to CompositionHost.Initialize.