【问题标题】:MEF property injection doesn't occur不会发生 MEF 属性注入
【发布时间】:2012-02-01 11:16:24
【问题描述】:

从导入的属性中检索信息时遇到问题。调用 .ComposeParts() 后,该属性仍然为空,但组合正常,因为之后我可以调用 .GetExportedValues() 并获得所需的实例。代码如下:

引导程序进行组合

 [Export]
public class Bootstrapper
{
    public void Run()
    {
        doComposition();
    }

    private void doComposition()
    {
        var catalog = new AggregateCatalog();

        catalog.Catalogs.Add(new DirectoryCatalog("./Applications"));
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(Loader).Assembly));

        Container = new CompositionContainer(catalog);
        // Apps = Container.GetExportedValues<IApplication>(); - this gets me the IApplication(s), but I dont understand why Apps isn't injected automatically
        Container.ComposeParts(catalog);
        IEnumerable<IApplication> app = Container.GetExportedValues<IApplication>();
    }

    public CompositionContainer Container { get; set; }

    private IEnumerable<IApplication> apps;

    [ImportMany(typeof(IApplication))]
    public IEnumerable<IApplication> Apps
    {
        get { return apps; }
        set
        {
            apps = value;
        }
    }

实现 IApplication 的类之一的签名

[Export(typeof(IApplication))]
public class MDFApplication : IApplication {...}

不胜感激,万分感谢。

【问题讨论】:

    标签: c# dependency-injection mef property-injection


    【解决方案1】:

    您永远不会调用任何代码来编写您的 Bootstrapper 类。 ComposeParts 将创建目录,它不会创建或组合任何类,除非您特别要求它们。

    当您调用 GetExportedValues 时,容器不会搜索所有需要导入的成员。它要么返回一个已经存在的实例,要么创建一个新实例,满足其所有导入属性。

    换句话说,以下代码将返回一个完全构造的 Bootstraper 类:

            var b= Container.GetExportedValue<Bootstrapper>();
            Debug.Assert(b.Apps!=null);            
    

    为了组合一个已经存在的对象,你需要调用 SatisfyImportsOnce 方法。如果可能,这将找到所有导入并满足它们。例如

            Container.SatisfyImportsOnce(this);
            Debug.Assert(this.Apps != null);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 2012-09-03
      • 2011-08-17
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多