我使用 CompositionBatch 将可组合部分添加到容器中,然后通过重新组合将其删除。一切都很好,组合和重组。但我的问题是底层对象没有被处置。我的代码如下所示:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export]
public class NonShared : IDisposable
{
public NonShared()
{
Console.WriteLine("Constructor of NonShared");
}
public void Dispose()
{
Console.WriteLine("Disposing NonShared");
}
}
class Program : IPartImportsSatisfiedNotification
{
[Import(AllowDefault=true, AllowRecomposition=true)]
private NonShared _nonShared;
public void OnImportsSatisfied()
{
Console.WriteLine("Program.OnImportsSatisfied()");
}
static void Main()
{
new Program().Run();
}
private void Run()
{
var partDefinition = AttributedModelServices.CreatePartDefinition(typeof(NonShared), null);
var exportingPart = partDefinition.CreatePart();
var addingBatch = new CompositionBatch();
addingBatch.AddPart(this);
addingBatch.AddPart(exportingPart);
var container = new CompositionContainer();
container.Compose(addingBatch);
// Do something.
var removingBatch = new CompositionBatch();
removingBatch.RemovePart(exportingPart);
container.Compose(removingBatch);
}
}
我希望调用 Nonshared.Dispose() ,但事实并非如此。正如AddPart/RemovePart 的部件生命周期所描述的,在这种情况下应该处理非共享部件。我的代码中有一些错误吗?