Exporting multiple interfaces using MEF with one instance

I have a class that implements two interfaces, A and B:

public class Test
{
    public Test()
    {
        Usage<IA> x = new Usage<IA>();
        Usage<IB> y = new Usage<IB>();
        var b = x.Implementation.Value.Equals(y.Implementation.Value);
    }
}

public interface IA { }
public interface IB { }

[Export(typeof(IA))]
[Export(typeof(IB))]
public class Impl : IA, IB
{
    public Impl()
    {

    }
}

public class Usage<T>
{
    public Usage()
    {
        CompositionContainer c = new CompositionContainer(new AssemblyCatalog(this.GetType().Assembly));
        c.ComposeParts(this);

        var x = Implementation.Value.ToString();
    }

    [Import]
    public Lazy<T> Implementation { get; set; }
}

      

The problem is that both properties have their own instance of the Impl class. I want them to point to the same instance. I tried to accomplish this with help CreationPolicy.Shared

, but that didn't work either. Any idea what I am doing wrong or is this not a supported script?

+3


source to share


1 answer


The problem is that you are using a different CompositionContainer for each instance of the Usage class. Export instances will not be used between different containers.



Richard Deming

+1


source







All Articles