github twitter linkedin email
Using MEF with Inheritance, the easy way
Jun 14, 2010
2 minutes read

Consider the class:

public class Vehicle<T> where T: IPropulsionEngine
{
    [Import()]
    public T PropulsionType { get; set; }

    [Import()]
    public IFuel<T> PropulsionFuel { get; set; }
}

The interesting thing here is that we are importing items that have an open generic declaration.

I’ve got a propulsion engine interface, and another interface that is specifically for gasoline engines:

public interface IPropulsionEngine
{
    string fuel { get; }
    int MaxRPM { get; }
}

[InheritedExport]
public interface IGasolineEngine : IPropulsionEngine
{
}

I’ve also got a fuel interface for any propulsion engine:

[InheritedExport]
public interface IFuel<T> where T : IPropulsionEngine
{
}

The interesting part here is the InheritedExport attribute. It means that whatever class that implements the class will be visible to MEF.

Consider the following classes:

public abstract class PropulsionEngine : IPropulsionEngine
{
    public abstract string fuel { get; }
    public abstract int MaxRPM { get; }
}

public class GasolineEngine : PropulsionEngine, IGasolineEngine
{

    public override string fuel
    {
        get { return "Gasonline"; }
    }

    public override int MaxRPM
    {
        get { return 3600; }
    }
}

public class Gasoline : IFuel<IGasolineEngine>
{
}

These classes implement the interfaces, but are not marked with any MEF attributes.

Yet, when I perform this unit test:

[TestMethod]
public void TestMethod1()
{
    AssemblyCatalog cat = new AssemblyCatalog(Assembly.GetExecutingAssembly());
    CompositionContainer c = new CompositionContainer(cat);

    Vehicle<IGasolineEngine> myVehicle = new Vehicle<IGasolineEngine>();
    c.ComposeParts(myVehicle);  

    Assert.IsNotNull(myVehicle.PropulsionType);
    Assert.IsNotNull(myVehicle.PropulsionFuel);
}

The test is successful!

This is run against MEF included in .net 4


Tags: MEF

Back to posts