Use classes from another MEF assembly without referencing to it

最后都变了- 提交于 2019-12-22 10:06:49

问题


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 data types from another assemblies without referencing to it? Is there such mechanism supported by MEF?


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/6290650/use-classes-from-another-mef-assembly-without-referencing-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!