0

从导入的属性中检索信息时出现问题。调用 .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 {...}

任何指针表示赞赏,非常感谢。

4

1 回答 1

2

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

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

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

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

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

        Container.SatisfyImportsOnce(this);
        Debug.Assert(this.Apps != null);
于 2012-02-01T11:39:39.017 回答