gpt4 book ai didi

.net - 基类中的 MEF 的 ImportMany 从所有程序集中导入所有导出 - 如何防止这种情况发生?

转载 作者:行者123 更新时间:2023-12-01 06:18:39 24 4
gpt4 key购买 nike

我正在使用 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 编写 MyAMyB 时,每个都包含来自两个程序集的导出的 IDependency-ies !我只希望 MyA 包含导出 DependencyA1DependencyA2,与 MyB 相同。

我知道我可能应该为此使用依赖项注入(inject)容器,但我希望可以使用 MEF?

最佳答案

在另一个作品的 Nose 底下做一个作品是非常讨厌的;)。

所以我会决定手动调用 container.GetExportedValues 并在构造函数中自行设置属性,这样您就可以一起摆脱 [ImportMany]。并且它没有在外部成分上被操纵。

HTH爱丽儿

关于.net - 基类中的 MEF 的 ImportMany 从所有程序集中导入所有导出 - 如何防止这种情况发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12128940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com