• How does Unity.Resolve know which constructor to use?


    Question:

        

    Given a class with several constructors - how can I tell Resolve which constructor to use?

    Consider the following example class:

    public class Foo
    {
        public Foo() { }
        public Foo(IBar bar)
        {
            Bar = bar;
        }
        public Foo(string name, IBar bar)
        {
            Bar = bar;
            Name = name;
        }
        public IBar Bar { get; set; }        
        public string Name { get; set; }
    }

    If I want to create an object of type Foo using Resolve how will Resolve know which constructor to use? And how can I tell it to use the right one? Let's say I have a container with an IBar registered - will it understand that it should favor the constructor taking IBar? And if I specify a string too - will it use the (string, IBar) constructor?

    Foo foo = unityContainer.Resolve<Foo>();

    And please ignore the fact that it would probably be easier if the class just had a single constructor...

    Answer:

     When a target class contains more than one constructor, Unity will use the one that has the InjectionConstructor attribute applied. If there is more than one constructor, and none carries the InjectionConstructor attribute, Unity will use the constructor with the most parameters. If there is more than one such constructor (more than one of the “longest” with the same number of parameters), Unity will raise an exception.

  • 相关阅读:
    嵌入式C程序基础与编程结构
    英特尔图形处理器第8代架构
    用servlet打内容到网页上
    servlet获取多个同名参数
    JAVA之复制数组
    用JAVA写一个简单的英文加密器
    Tomcat使用
    JAVA,字符串替换
    使用自己的域名解析博客园地址(CSDN也可以)
    错误笔记20181124
  • 原文地址:https://www.cnblogs.com/Qiaoyq/p/4244394.html
Copyright © 2020-2023  润新知