MEF怎么删除部件,有一段代码始终运行不正确?
http://mef.codeplex.com/wikipage?title=Parts%20Lifetime&referringTitle=Guide
从上面拷贝的代码运行始终不正确,怎么才能正确的删除部件?
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
class Program
{
static void Main(string[] args)
{
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
var container = new CompositionContainer(catalog);
var root = new Root();
// add external part
container.ComposeParts(root);
// ... use the composed root instance
// removes external part
var batch = new CompositionBatch();
//这里始终报错???
batch.RemovePart(root);
container.Compose(batch);
}
}
public class Root
{
[Import(RequiredCreationPolicy = CreationPolicy.NonShared)]
public NonSharedDependency Dep { get; set; }
}
[Export, PartCreationPolicy(CreationPolicy.NonShared)]
public class NonSharedDependency : IDisposable
{
public NonSharedDependency()
{
}
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
var container = new CompositionContainer(catalog);
var root = new Root();
container.ComposeParts(root);
var batch = new CompositionBatch();
var part = batch.AddExportedValue<NonSharedDependency>(new NonSharedDependency());
container.Compose(batch);
Console.ReadLine();
}
}
public class Root
{
[Import(RequiredCreationPolicy = CreationPolicy.NonShared, AllowRecomposition=true)]
public NonSharedDependency Dep { get; set; }
}
[Export, PartCreationPolicy(CreationPolicy.NonShared)]
public class NonSharedDependency : IDisposable
{
public NonSharedDependency()
{
Console.WriteLine("Created an instance of NonSharedDependency");
}
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
}
var batch = new CompositionBatch();
var part = batch.AddExportedValue<NonSharedDependency>(new NonSharedDependency());
container.Compose(batch);
[其他解释]
你好,我试了一下,可是还是没有删除:
// removes external part
var batch = new CompositionBatch();
var part = batch.AddExportedValue(root);
//这里始终报错???
batch.RemovePart(part);
container.Compose(batch);