me2配置每个模块中的注册

本文关键字:注册 模块 配置 me2 | 更新日期: 2023-09-27 18:06:15

好的,所以我在使用。net 4.5的c# WPF应用程序中使用Caliburn Micro和Mef2。我想知道是否有任何方法可以在单独的dll中配置我的Mef2注册,然后在我的主dll中使用它们。基本上,dll将配置自己的导入和导出。

例如:

RegistrationBuilder builder = new RegistrationBuilder();
        builder.ForTypesDerivedFrom<IShell>().Export<IShell>().SetCreationPolicy(CreationPolicy.Shared);
        builder.ForTypesDerivedFrom<IFindProducts>().Export<IFindProducts>().SetCreationPolicy(CreationPolicy.Shared);
        builder.ForTypesMatching(t => t.Name.EndsWith("ViewModel")).Export().SetCreationPolicy(CreationPolicy.NonShared);
        return builder;

在每个dll中,但我卡住了合并所有注册到一个RegistrationBuilder,然后传递到每个目录的点。

me2配置每个模块中的注册

一种方法是将RegistrationBuilder传递给每个程序集进行更新。这可以通过添加如下接口来实现:

public interface IRegistrationUpdater
{
    void Update(RegistrationBuilder registrationBuilder);
}

在契约程序集中。所有需要注册MEF2约定的程序集都将引用此文件。例如:

public class RegistrationUpdater: IRegistrationUpdater
{
    public void Update(RegistrationBuilder registrationBuilder)
    {
        if (registrationBuilder == null) throw new ArgumentNullException("registrationBuilder");
        registrationBuilder.ForType<SomeType>().ImportProperty<IAnotherType>(st => st.SomeProperty).Export<ISomeType>();
        registrationBuilder.ForType<AnotherType>().Export<IAnotherType>();
    }
}

,其中SomeType实现ISomeType, AnotherType实现IAnotherTypeIAnotherType不需要零件。ISomeType需要IAnotherType部件。

然后在主程序中,你需要找到可用的IRegistrationUpdaters,使用如下命令:

static IEnumerable<IRegistrationUpdater> GetUpdaters()
{            
    var registrationBuilder = new RegistrationBuilder();
    registrationBuilder.ForTypesDerivedFrom<IRegistrationUpdater>().Export<IRegistrationUpdater>();
    using (var catalog = new DirectoryCatalog(".", registrationBuilder))
    using (var container = new CompositionContainer(catalog))
    {
        return container.GetExportedValues<IRegistrationUpdater>();
    }  
}

,然后可以使用它来迭代每个更新程序并调用IRegistrationUpdater.Update(RegistrationBuilder)

var mainRegistrationBuilder = new RegistrationBuilder();
foreach (var updater in GetUpdaters())
{
    updater.Update(mainRegistrationBuilder);
}
var mainCatalog = new DirectoryCatalog(".", mainRegistrationBuilder);
var mainContainer = new CompositionContainer(mainCatalog);
var s = mainContainer.GetExportedValue<ISomeType>();