2

考虑接口:

public interface IOne{}
public interface ITwo{}
public interface IBoth : IOne, ITwo{}

和类

public class Both : IBoth{}

但是当我需要解析基本接口时,我需要在容器中注册两个接口

<register type="IOne" MapTo="Both"/>
<register type="ITwo" MapTo="Both"/>

问题是 - 我可以以这样的方式对注册进行重复数据删除:

<register type="IBoth" MapTo="Both"/>

但是从不同的接口在不同的地方解决它:

var o = containet.Resolve<IOne>();
var t = containet.Resolve<ITwo>();

由于这种情况不起作用,我可以以任何其他方式做这样的把戏吗?...

4

1 回答 1

3

简短的回答:你不能。长答案:您可以编写一个自定义容器扩展来为您完成这种技巧。

[TestMethod]
public void TestMethod1()
{
  var container = new UnityContainer().AddNewExtension<DeduplicateRegistrations>();
  container.RegisterType<IBoth, Both>();
  IThree three = container.Resolve<IThree>();
  Assert.AreEqual("3", three.Three());
}

public class DeduplicateRegistrations : UnityContainerExtension
{
  protected override void Initialize()
  {
    this.Context.Registering += OnRegistering;
  }
  private void OnRegistering(object sender, RegisterEventArgs e)
  {
    if (e.TypeFrom.IsInterface)
    {
      Type[] interfaces = e.TypeFrom.GetInterfaces();
      foreach (var @interface in interfaces)
      {
        this.Context.RegisterNamedType(@interface, null);
        if (e.TypeFrom.IsGenericTypeDefinition && e.TypeTo.IsGenericTypeDefinition)
        {
          this.Context.Policies.Set<IBuildKeyMappingPolicy>(
            new GenericTypeBuildKeyMappingPolicy(new NamedTypeBuildKey(e.TypeTo)),
            new NamedTypeBuildKey(@interface, null));
        }
        else
        {
          this.Context.Policies.Set<IBuildKeyMappingPolicy>(
            new BuildKeyMappingPolicy(new NamedTypeBuildKey(e.TypeTo)),
            new NamedTypeBuildKey(@interface, null));
        }
      }
    }
  }
}
public class Both : IBoth
{
  public string One() { return "1"; }
  public string Two() { return "2"; }
  public string Three() { return "3"; }
}
public interface IOne : IThree
{
  string One();
}
public interface IThree
{
  string Three();
}
public interface ITwo
{
  string Two();
}
public interface IBoth : IOne, ITwo
{
}

您将需要微调扩展以捕获接口注册,例如IDisposable或覆盖给定接口的现有注册。

于 2012-10-04T10:08:01.697 回答