Is it possible to deduplicate registration in unity?

前端 未结 1 1241
别那么骄傲
别那么骄傲 2021-01-15 03:21

Consider interfaces:

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

And class

public         


        
1条回答
  •  -上瘾入骨i
    2021-01-15 03:42

    Short answer: You can't. Long answer: You can write a custom container extension that does this kind of trick for you.

    [TestMethod]
    public void TestMethod1()
    {
      var container = new UnityContainer().AddNewExtension();
      container.RegisterType();
      IThree three = container.Resolve();
      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(
                new GenericTypeBuildKeyMappingPolicy(new NamedTypeBuildKey(e.TypeTo)),
                new NamedTypeBuildKey(@interface, null));
            }
            else
            {
              this.Context.Policies.Set(
                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
    {
    }
    

    You will need to fine-tune the extension in order to catch registration of interfaces like IDisposable or overwriting an already existing registration for a given interface.

    0 讨论(0)
提交回复
热议问题