日期:2014-05-17  浏览次数:20973 次

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");
    }
}

------最佳解决方案--------------------
引用:
public void Dispose() 
    { 
        Console.WriteLine("Disposed"); 
    }
例子的意思就是Dispose没有调用啊?删除部件后就应该调用啊?

引用:引用:
你好,我试了一下,可是还是没有删除:
C# c……


试试下面这段代码。

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();