开发者

Use classes from another MEF assembly without referencing to it

I have 2 MEF components. Let it be component A and component 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.

Currently I see MEF allows instantiating an object automatically using [Import]. It uses interface which requires to be referenced to.

Can I use 开发者_JS百科data types from another assemblies without referencing to it? Is there such mechanism supported by MEF?


You can instantiate a class via reflection without having a hard reference to the file. You don't need MEF for that.


There are a couple of ways to do this.

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).

In B, export the type using this interface.

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.

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>();


Then I would like to instantiate object of the class manually.

Maybe you would be better of to do it manually by loading the assembly and pick the desired type from it instead of using MEF.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜