一种方法是将 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
实施IAnotherType
。IAnotherType
不需要零件。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>();