使用MEF在ImportMany上重新构建问题

时间:2010-08-14 18:38:45

标签: c# .net mef

我在一个为其定义了importManyAttribute的类上定义了一个属性,声明如下:

public const string FontStyleProvidersPropertyName = "FontStyleProviders";
[ImportMany(typeof(IFontStyleProvider), RequiredCreationPolicy = CreationPolicy.Shared, AllowRecomposition=true)]
public List<IFontStyleProvider> FontStyleProviders { get; set; }

第一次运行我按如下方式构建我的合成容器

private CompositionContainer BuildCompositionContainer()
{
    //build our composable parts catalog
    Assembly executingAssembly = Assembly.GetExecutingAssembly();
    CompositionContainer applicationContainer;
    string localPath = Path.GetDirectoryName(executingAssembly.Location);

    try
    {
        aggregateCatalog = new AggregateCatalog();
        aggregateCatalog.Catalogs.Add(new AssemblyCatalog(executingAssembly));

        if (!Directory.Exists(Path.Combine(localPath, ApplicationExtensionsPath)))
        {
            Directory.CreateDirectory(Path.Combine(localPath, ApplicationExtensionsPath));
        }

        exportsCatalog = new DirectoryCatalog(Path.Combine(localPath, ApplicationExtensionsPath));

        aggregateCatalog.Catalogs.Add(new DirectoryCatalog(Path.Combine(localPath, ApplicationExtensionsPath)));

        //create a composition container
        return applicationContainer = new CompositionContainer(aggregateCatalog);
    }
    catch (Exception e)
    {
        Debug.Fail("Catalog Construction Failed", e.StackTrace);
        throw;
    }
}

此时,一切都按预期工作,但我似乎无法在“this”类实例上触发重组。我有一个导入方法如下:

private void Import()
{
    exportsCatalog.Refresh();
    CompositionBatch batch = new CompositionBatch();
    batch.AddPart(this);
    applicationContainer.Compose(batch);

    var copy = PropertyChanged;
    if (copy != null)
    {
        copy(this, new PropertyChangedEventArgs(FontStyleProvidersPropertyName));
        copy(this, new PropertyChangedEventArgs(MessageContainerViewModelsPropertyName));
    }
}

它在exportsCatalog使用的ApplicationExtensionPath文件夹中找到了新的类型,但它实际上从未重新构建FontStyleProviders(或MessageContainerViewModels)

我已经阅读了几次这些文件,我似乎无法弄明白为什么。

1 个答案:

答案 0 :(得分:2)

问题是您实际上没有将您调用Refresh()的目录添加到AggregateCatalog中。改变这个:

exportsCatalog = new DirectoryCatalog(Path.Combine(localPath, ApplicationExtensionsPath));
aggregateCatalog.Catalogs.Add(new DirectoryCatalog(Path.Combine(localPath, ApplicationExtensionsPath)));

对此:

exportsCatalog = new DirectoryCatalog(Path.Combine(localPath, ApplicationExtensionsPath));
aggregateCatalog.Catalogs.Add(exportsCatalog);

此外,一旦你的班级成立,你就不应该再写一次。只需调用exportsCatalog.Refresh()就足以导致重组。