【问题标题】:Tracking instances created by a MEF container跟踪由 MEF 容器创建的实例
【发布时间】:2011-03-29 00:25:48
【问题描述】:

我正在使用 MEF 创建同一个导出的多个实例。

我想跟踪我创建的实例,并且正在查询容器或使用重新组合的集合,但我从来没有得到我的实例...

代码如下:

interface IFoo{};
[Export(typeof(IFoo)),PartCreationPolicy(CreationPolicy.NonShared)]
class Foo{};

  class FooTracker{
     CompositionContainer _container; 
     int HowManyValues()
     {
       // this always returns 1 and invokes a constructor
       return _container.GetExportedValue<IFoo>().Count();
     }

     int HowManyExports(){
       // idem
       return _container.GetExports<IFoo>().Count();
     }

     // idem
     [ImportMany(AllowRecomposition=true,AllowRecomposition=true)]
     protected IEnumerable<IFoo> Foos { get; set; }
  }

我想要的是已经存在的实例,如果没有的话就创建一个新的。

谢谢, 弗洛里安

【问题讨论】:

    标签: c# ioc-container mef


    【解决方案1】:

    MEF 不提供此功能。您可以通过让 IFoo 的每个实现导入一个 IFooTracker 并在 IFooTracker 中调用一个方法来注册 IFoo。

    【讨论】:

    • +1 叮叮。使您的 IFooTracker 静态和 IDisposable 以清理注册,但这是您跟踪任何实例的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    相关资源
    最近更新 更多