Search code examples
c#.net.net-4.0componentsmef

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


Solution

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