[Import] 和 _container.GetExportedValue<>() 之间有什么区别吗?
Any differences between [Import] and _container.GetExportedValue<>()?
使用 MEF,假设有一个名为 FooType
的 class,我在其上应用了 [Export]
属性。现在,我想在我的代码中的其他地方导入这个 FooType
以使用它。
我已经尝试了这两种解决方案:
[Import]
public FooType Foo { get; set; }
private void MyMethod()
{
Foo.DoSomething();
}
和
private void MyMethod()
{
// _container is of type CompositionContainer and comes from the [ImportingConstructor]
_container.GetExportedValue<FooType>().DoSomething();
}
这两个都有效,正确调用了 FooType
的 DoSomething()
方法。所以这让我想知道:
- 这两种解决出口的方式真的很相似吗?或者有什么区别吗?
- 两者之间有推荐的解决方案吗?
[Import] 基本上会导致 MEF 调用 GetExportedValue 并将其分配给 属性 或字段。也就是说,大多数时候您不希望您的对象访问您的容器。在您的第二个示例中,您说您通过 ImportingConstructor 导入了容器本身。我通常只会通过构造函数导入 FooType。我也总是更喜欢构造函数注入而不是 属性 注入。它使对象的先决条件完全清楚,您的导入可以存储在只读属性中。
使用 MEF,假设有一个名为 FooType
的 class,我在其上应用了 [Export]
属性。现在,我想在我的代码中的其他地方导入这个 FooType
以使用它。
我已经尝试了这两种解决方案:
[Import]
public FooType Foo { get; set; }
private void MyMethod()
{
Foo.DoSomething();
}
和
private void MyMethod()
{
// _container is of type CompositionContainer and comes from the [ImportingConstructor]
_container.GetExportedValue<FooType>().DoSomething();
}
这两个都有效,正确调用了 FooType
的 DoSomething()
方法。所以这让我想知道:
- 这两种解决出口的方式真的很相似吗?或者有什么区别吗?
- 两者之间有推荐的解决方案吗?
[Import] 基本上会导致 MEF 调用 GetExportedValue 并将其分配给 属性 或字段。也就是说,大多数时候您不希望您的对象访问您的容器。在您的第二个示例中,您说您通过 ImportingConstructor 导入了容器本身。我通常只会通过构造函数导入 FooType。我也总是更喜欢构造函数注入而不是 属性 注入。它使对象的先决条件完全清楚,您的导入可以存储在只读属性中。