MEF对象生命周期

时间:2014-06-27 00:33:21

标签: c# mef

我有一个名为Foo的课程:

using System;
using System.ComponentModel.Composition;

namespace MefTest
{
    [Export]
    internal class Foo 
    {
        public Foo()
        {
            Console.WriteLine("created foo");
        }

        ~Foo()
        {
            Console.WriteLine("Dead");
        }            
    }
}

它是这样创造的:

using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

namespace MefTest
{
    internal class Program
    {
        public static void Main()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            var container = new CompositionContainer(catalog);

            //EDIT: my problem, this returns Lazy<Foo> not Foo. Since I didn't call foo1.Value it was never actually created
            var foo1 = container.GetExport<Foo>(); 

            container.ReleaseExport(foo1);

            foo1 = null;

            GC.Collect();

            Console.Read();
        }
    }
}

但它似乎永远不会被处理掉。我尝试添加一个IDisposible接口,没有任何运气。

如何确保正确清理?我认为ReleaseExport会这样做,但析构函数永远不会被调用,所以它似乎永远不会被清除。

我已阅读http://mef.codeplex.com/wikipage?title=Parts%20Lifetime,但我似乎无法看到上述代码的问题。

1 个答案:

答案 0 :(得分:1)

您遇到的问题是Foo是共享导出。如果您希望按原样处理,则可以在其上实施IDisposable,然后在容器上调用Dispose

另一种选择是将Foo标记为非共享,这将导致ReleaseExport在其上调用Dispose方法。

[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
internal class Foo 
{
    public Foo()
    {
        Console.WriteLine("created foo");
    }

    ~Foo()
    {
        Console.WriteLine("Dead");
    }            
}

以上内容在您提供的链接的“Scoped操作和资源的早期回收”部分中得到了很好的解释。请记住,如果您不提供PartCreationPolicy属性,则默认情况下会共享导出。

相关问题