使用 MEF 为同一导入提供不同的值
这个问题与MEF的使用有关。
我想在这两种情况下为相同的导入提供不同的值在
[Export("A1", typeof(IA))]
[Export("A2", typeof(IA))]
class A : IA
{
[Import("B")]
public IB B;
}
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IA))]
class A : IA
{
[Import]
public IB B;
}
上面的两种情况下,我想用不同的值满足 IB
的导入,即当我在第一种类型中执行此操作时导出
var a1 = Container.GetExportedValue<IA>("A1");
var a2 = Container.GetExportedValue<IA>("A1");
或第二次导出中的 this
var a1 = Container.GetExportedValue<IA>();
var a2 = Container.GetExportedValue<IA>();
我希望 A a1
和 a2
的两个实例具有不同的 IB
值。我不想使用 ImportMany
,因为这样我必须决定选择哪一个,并且我希望将该逻辑保留在 A
类之外。
与这些导出相关的两个场景是,我希望有一个通用的通用视图来处理实现某些接口的不同类型的视图模型以及提供某些要使用不同配置参数进行配置的服务的类的不同实例。
This question is pertaining to the usage of MEF.
I want to provide different values for the same import in these two scenarios
[Export("A1", typeof(IA))]
[Export("A2", typeof(IA))]
class A : IA
{
[Import("B")]
public IB B;
}
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(IA))]
class A : IA
{
[Import]
public IB B;
}
In both of the two scenarios above, I want to satisfy the import of IB
with different values that is when I do this in the first type of export
var a1 = Container.GetExportedValue<IA>("A1");
var a2 = Container.GetExportedValue<IA>("A1");
or this in the second export
var a1 = Container.GetExportedValue<IA>();
var a2 = Container.GetExportedValue<IA>();
I want the two instance of A a1
and a2
to have different values of IB
. I don't want to use ImportMany
because then I have to decide which one to choose and I want to keep that logic out of class A
.
The two scenarios related to these exports are that I want to have a common generic view to work with different types of view models implementing some interface and different instances of a class that provides some service to be configured with different configuration parameters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许您正在寻找这样的东西?
然而,MEF 并不是真正为对合成进行如此细粒度的控制而设计的。您可以尝试使用 Autofac 等替代方案,它与 MEF 集成良好。
Perhaps you are looking for something like this?
However, MEF isn't really designed for such fine-grained control over the composition. You could try an alternative like Autofac, which integrates well with MEF.
我不完全理解您想要做什么,但我认为您可以通过在 IB 导入上指定 NonShared 创建策略来完成此操作。
I don't entirely understand what you are trying to do, but I think you may be able to do it by specifying a creation policy of NonShared on the IB import.