This project has moved. For the latest updates, please go here.

Ensuring MEF to compose an instance only once

Feb 21, 2011 at 5:36 PM


my scenario is as follows: let's assume we have two classes/objects - A and B that require to be composed by MEF after instantiation. In short, something like this:

A { //some imports } class B { [Import] A importedA; }

What I find problematic is composition of A. There are two ways how it could be composed (depending on how it is used):

1.  If I need to directly use A somewhere in the application, I need to ensure all imports are satisfied, when I type:

A a = new A();

 I guess a good idea is to self-compose A by calling an appropriate method from the constructor.

2. When I compose B, it automatically composes its imported parts (so A is composed too).

These two mechanisms are needed to keep things working in all use cases. Howeve, they seem to overlap. If B is composed (as in point 2) A is composed twice. Firstly, when the constructor of A is called to self-compose. Secondly, when B requests a composed instance of A. Such a problem in design occurs very often across the application, so I think I'm missing something essential. I made a quick app to check it and a CompositionException is thrown when I call Compose(B):

The ComposablePart of type {0} cannot be recomposed because it is in an invalid state. It can only be recomposed if it has already been fully previewed or composed.


Is there a way to ensure that a certain instance will be composed only once without calling an exception? What is the right approach to deal with this issue?

I hope I was writing clear. Thanks in advance!