我有一个类实现了两个接口,A和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; }
}
我的问题是这两个属性都有自己的Impl类实例。我想让它们指向同一个实例。我试图通过CreationPolicy.Shared
来实现,但也没有用。你觉得我的操作有什么不对,还是这个情况不被支持?
[PartCreationPolicy(CreationPolicy.Shared)]
添加到Impl
类中,结果和预期一样正常;ImplA
和ImplB
都被设置为Impl
的同一个实例。 - Richard DeemingUsage
类的实例使用了不同的CompositionContainer
。导出的实例将不会在不同的容器之间共享。 - Richard Deeming