Pregunta

I have a class which 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 I have 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 the CreationPolicy.Shared, but that didn't work either. Any idea what I'm doing wrong, or is this a not supported scenario?

¿Fue útil?

Solución

The problem is that you're using a different CompositionContainer for each instance of the Usage class. Instances of an export will not be shared between different containers.

Richard Deeming

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top