I'm using constructor injection with MEF Composition Container and I want to know how can I make the CompositionContainer inject itself on the instance of the object he is providing.
Asked
Active
Viewed 1,086 times
1
-
By doing this you are essentially moving away from dependency injection and towards the [service locator pattern](http://en.wikipedia.org/wiki/Service_locator_pattern). This may have a detrimental effect on the maintainability of your application. – MattDavey Nov 20 '13 at 10:04
2 Answers
2
You can use one of the CompositionContainer.ComposeExportedValue methods to create a part from a given object.
Here's a sample:
class Program
{
static void Main(string[] args)
{
var container = new CompositionContainer(new ApplicationCatalog());
Console.WriteLine("Main: container [{0}]", container.GetHashCode());
container.ComposeExportedValue<CompositionContainer>(container);
var exp = container.GetExportedValue<ExportThatNeedsContainer>();
Console.ReadKey();
}
}
[Export]
public class ExportThatNeedsContainer
{
[ImportingConstructor]
public ExportThatNeedsContainer(CompositionContainer cc)
{
Console.WriteLine("ExportThatNeedsContainer: cc [{0}]", cc.GetHashCode());
}
}
This works, however injecting the container to a part, as far as I know, is not a "normal" use-case of MEF.

Panos Rontogiannis
- 4,154
- 1
- 24
- 29
-
3+1 for "injecting the container to a part, as far as I know, is not a "normal" use-case of MEF". This would be a red flag with any IoC container. – MattDavey Nov 20 '13 at 10:02
0
I'm not sure it could work. Imagine you have a container with three classes, one of them also contains the container itself, which contains the three classes. It would be a stackoverflow :)

Andras Sebo
- 1,120
- 8
- 19