开发者

does exporting two times in mef point to the same object

[Export]
[Export(typeof(IClass))
public Class : IClass

Can I expect the s开发者_JS百科ame singleton when I use constructor injection for Class and IClass?


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜