[Export]
[Export(typeof(IClass))
public Class : IClass
当我为Class和IClass使用构造函数注入时,我可以期待相同的单例吗?
答案 0 :(得分:4)
是的,无论导出的数量如何,每个类型都指定CreationPolicy.Shared
,这意味着Export
和Export(typeof(IClass))
的实际运行时类型结果。您可以通过示例看到这一点:
public interface IMyClass
{
string Name { get; set; }
}
[Export]
[Export(typeof(IMyClass))]
public class MyClass : IMyClass
{
private static int count;
public MyClass()
{
count++;
Name = "Instance " + count;
}
public string Name { get; set; }
}
var container = new CompositionContainer(
new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var instance1 = container.GetExportedValue<MyClass>();
var instance2 = container.GetExportedValue<IMyClass>();
// should be true.
bool referenceEquals = object.ReferenceEquals(instance1, instance2);
// should also be true.
bool nameEquals = instance1.Name == instance2.Name;