The PartCreationPolicy allows you to declare a shared or non-shared export. The RequiredCreationPolicy allows you to declare a shared or non-shared import. The MEF CompositionContainer tracks the lifetime of objects, so it will either share an existing instance
or create one on every import.
I'm having a difficult time to find the right approach to a typical scenario:
- a Silverlight application has a main window and lots of views ("document views").
- at any time the user could have opened several instances of a particular view, but with different instance data. So the user would for instance be able to look at the product details of various products (compare with MDI-concepts).
- a view has imported dependencies. Think about the View-Model-ViewModel pattern. It might also have a local event aggregator when the view itself is a composite view.
- the application has a global event aggregator (or better said: message bus). For the sake of the sample, this event aggregator is of the same type as the view event aggregator.
How can I create an object tree per view instance where I have globally scoped, application wide instances and locally scoped instances? Should every dependency be imported or can we use a ServiceLocator for high level dependencies? What is the best approach
to hide the CompositeContainer calls?
I assume I have to create a new child CompositeContainer whenever I create a new view instance. So if the user starts a new activity, it will start a new view. The application creates a child container, news up the view and registers the view in the
child container. This way I'm able to create a local instance of the view and all of its dependencies. I assume it would make sense for the view to rely on an imported CompositeContainer, so it can use the right container.
An alternative would be to make use of the PartCreator at the view level. But when the PartCreator creates the part, what will happen when such a type needs to be resolved by the container? Will the container exclude this instance in it's resolution
The preview 7 drop has an ImageViewer sample where classes call PartsInitializer in their constructor to resolve dependencies. This is great, since now you can simply new up this type and you bypass the CompositeContainer in your code. But how will PartsInitializer
resolve the CompositeContainer? When you call the PartsInitializer in the constructor you risk that not all dependent types can be resolved, or?
In the ImageViewer example the View will be constructed via XAML and will be responsible to resolve the ViewModel (in my case), which is good. How can you prevent passing the (child)container reference and still exploit the PartsInitializer?