我正在使用 MEF 组合来自多个程序集的导出类型。我正在使用一个基类,它应该ImportMany
依赖于派生类中的指定。它看起来像这样:
底座组装:
public abstract class BaseClass
{
[ImportMany(typeof(IDependency)]
public IEnumerable<IDependency> Dependencies { get; private set; }
protected BaseClass()
{
var catalog = GetCatalog();
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
protected abstract ComposablePartCatalog GetCatalog();
}
大会 A:
[Export(typeof(BaseClass))]
public class MyA : BaseClass
{
protected override ComposablePartCatalog GetCatalog()
{
return new AssemblyCatalog(Assembly.GetExecutingAssembly());
}
}
[Export(typeof(IDependency)]
public class DependencyA1 : IDependency {}
[Export(typeof(IDependency)]
public class DependencyA2 : IDependency {}
组装 B:
[Export(typeof(BaseClass))]
public class MyB : BaseClass
{
protected override ComposablePartCatalog GetCatalog()
{
return new AssemblyCatalog(Assembly.GetExecutingAssembly());
}
}
[Export(typeof(IDependency)]
public class DependencyB1 : IDependency {}
[Export(typeof(IDependency)]
public class DependencyB2 : IDependency {}
然后我在基础程序集中编写所有内容:
static void Main(string[] args)
{
DirectoryCatalog catalog = new DirectoryCatalog(path, "*.dll");
var container = new CompositionContainer(catalog);
IEnumerable<BaseClass> values = container.GetExportedValues<BaseClass>();
// both BaseClass instances now have 4 Dependencies - from both Assemby A and Assembly B!
}
我遇到的问题是,当我使用 MEF 组合MyA
andMyB
时,每个都包含来自两个程序集的导出IDependency
-ies!我只想MyA
包含 exportDependencyA1
和DependencyA2
,与MyB
.
我知道我可能应该为此使用依赖注入容器,但我希望可以使用 MEF?