Reputation: 9171
[Export]
[Export(typeof(IClass))
public Class : IClass
Can I expect the same singleton when I use constructor injection for Class and IClass?
Upvotes: 1
Views: 101
Reputation: 61599
Yes, regardless of the number of exports, the CreationPolicy.Shared
is specified per type, which means as the actual runtime type resultant of Export
and Export(typeof(IClass))
. You can see this with an example:
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;
Upvotes: 4