2011-02-25 61 views
1

我已经构建了一个创建服务的MEF容器。我使用第一个容器中的这些服务构建了另一个MEF容器。问题是这些服务被添加到第二个容器时被重新组合。MEF重组子容器

[Export(typeof(IFoo))] 
public class Foo : IFoo 
{ 
    [Import(typeof(IServiceA))] 
    public IServiceA A { get; set; } 
} 

[Export(typeof(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); 

“创建服务A”大干快上时,容器创建,因为它试图重新构图富,我不希望它可以将上述组成的最后一行调用两次。

有没有人有解决这个问题?我已经明确地指定了AllowRecomposition = false,但这也不起作用。

回答

3

你想用父/子容器实现什么?在你显示的代码中,你实际上并没有创建父母和孩子,而是创建了两个不相关的容器。要真正创建一个子容器,请执行下列操作:

var childContainer = new CompositionContainer(parentContainer, childCatalog); 

然后在父母任何事情都会自动成为孩子提供(这样你就不必通过批处理将其添加)。您将需要一个不同的子目录,包含你想要在子目录中的部分。