使用来自另一个MEF组件类,而引用它 [英] Use classes from another MEF assembly without referencing to it

查看:244
本文介绍了使用来自另一个MEF组件类,而引用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个MEF组件。让它成为A组分和B组分。

I have 2 MEF components. Let it be component A and component B.

我需要的是能够访问来自组分B组分A类,而不引用它。然后我想手动实例化类的对象。

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允许使用[导入]自动实例化对象。它使用接口需要被引用到

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必须是在容器的目录。无论是引用程序集B明确地在 AssemblyCatalog ,或创建一个 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,; T>()在容器上。在code看起来是这样的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆