使用来自另一个 MEF 程序集的类而不引用它 [英] Use classes from another MEF assembly without referencing to it
问题描述
我有 2 个 MEF 组件.让它成为组件 A 和组件 B.
I have 2 MEF components. Let it be component A and component B.
我需要的是能够从组件 A 中的组件 B 访问一个类而不引用它.然后我想手动实例化该类的对象.
What I need is to be able to access a class from component B in component A without referencing to it. Then I would like to instantiate object of the class manually.
目前我看到 MEF 允许使用 [Import] 自动实例化对象.它使用需要引用的接口.
Currently I see MEF allows instantiating an object automatically using [Import]. It uses interface which requires to be referenced to.
我可以使用来自其他程序集的数据类型而不引用它吗?MEF是否支持这种机制?
Can I use data types from another assemblies without referencing to it? Is there such mechanism supported by MEF?
推荐答案
有几种方法可以做到这一点.
There are a couple of ways to do this.
首先,您需要定义两个程序集都可以理解的通用接口.这可能是这两个程序集都引用的PublicInterfaces"库,或者它可能在程序集 A 内部(B 引用 A,但不是相反).
First, you need to define a common interface that both assemblies understand. This could be a "PublicInterfaces" library that both of these assemblies reference, or it could be inside of assembly A (B references A, but not the other way around).
在B中,使用该接口导出类型.
In B, export the type using this interface.
B 必须在容器的目录中.在 AssemblyCatalog
中显式引用程序集 B,或者创建一个 DirectoryCatalog
并将其指向将包含程序集 B 的目录.
B has to be in the container's catalog. Either reference assembly B explicitly in an AssemblyCatalog
, or create a DirectoryCatalog
and point it at the directory that will contain assembly B.
在 A 中,不使用 Import 属性,而是在容器上的代码调用 GetExportedValue<T>()
.代码如下所示:
In A, instead of using Import attributes, in code call GetExportedValue<T>()
on the container. The code looks something like this:
// Known by A and B
public interface CommonInterface
{
// ...
}
// In B, not A
[Export(typeof(CommonInterface))]
public class BClass : CommonInterface
{
// ...
}
// In A where you want to manually create class B
CommonInterface objB = _container.GetExportedValue<CommonInterface>();
这篇关于使用来自另一个 MEF 程序集的类而不引用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!