MEF Recomposition of child containers
I've built a MEF container that creates a service. I build another MEF container with these services from the first container. The problem is those services get recomposed when being added to the second container.
[Export(typeof(IFoo))]
public class Foo : IFoo
{
[Import(typeof(IServiceA))]
public IServiceA A { get; set; }
}
[Export(typeo开发者_开发百科f(IServiceA))]
public class ServiceAImpl : IServiceA
{
public ServiceAImpl()
{
Console.Out.WriteLine("Service A Created");
}
}
//Create the parent container
var parentContainer = new CompositionContainer(Composer.AggregateCatalog);
IFoo foo = parentContainer.GetExportedValue<IFoo>();
//..... some work
//Create a child container providing it an existing instance of IFoo
var childContainer = new CompositionContainer(Composer.AggregateCatalog);
var batch = new CompositionBatch();
batch.AddPart(foo); //Add existing IFoo
//This causes a recomposition of IFoo resulting in
//a new instance of IServiceA to be created and injected
childContainer.Compose(batch);
"Service A Created" gets called twice on the last line above when the container creates the composition because it's trying to recompose Foo, which I don't want it to.
Does anyone have a solution to this? I've tried explicitly specifying AllowRecomposition=false too but that doesn't work either.
What are you trying to achieve with parent/child containers? In the code you show, you're not actually creating a parent and a child, you're creating two unrelated containers. To actually create a child container, do the following:
var childContainer = new CompositionContainer(childCatalog, parentContainer);
Then anything in the parent will automatically be available in the child (so you won't have to add it via a batch). You'll want a different catalog for the child container with the parts you want to be in the child.
精彩评论