Unity not using the default constructor of the class

后端 未结 3 413
情深已故
情深已故 2021-01-01 13:29

I have this class :

public class Repo
{
   public Repo() : this(ConfigurationManager.AppSettings[\"identity\"],       ConfigurationManager.AppSettings[\"pass         


        
3条回答
  •  梦毁少年i
    2021-01-01 14:20

    Unity by default picks the constructor with the most parameters. You have to tell Unity to use a different one explicitly.

    One way to do this is with the [InjectionConstructor] attribute like this:

    using Microsoft.Practices.Unity;
    
    public class Repo
    {
       [InjectionConstructor]
       public Repo() : this(ConfigurationManager.AppSettings["identity"], ConfigurationManager.AppSettings["password"])
       {
    
       }
    
       public Repo(string identity,string password)
       {
           //Initialize properties.
       }
    }
    

    A second way of doing this, if your opposed to cluttering up classes/methods with attributes, is to specify which constructor to use when configuring your container using an InjectionConstructor:

    IUnityContainer container = new UnityContainer();
    container.RegisterType(new InjectionConstructor());
    

    From the documentation:

    How Unity Resolves Target Constructors and Parameters

    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.

提交回复
热议问题