Unity不使用类的默认构造函数 [英] Unity not using the default constructor of the class

查看:222
本文介绍了Unity不使用类的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个课程:

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

    {

    }

   public Repo(string identity,string password)
   {
       //Initialize properties.
   }

}

我在网上添加了一行。

I added a line to web.config so that this type will be automatically constructed by Unity container.

但是在执行应用程序期间,我收到此错误消息:

but during the execution of my application, I receive this error message :

  "System.InvalidOperationException : the parameter identity could not be resolved when attempting to call constructor Repo(String identity, String password)  -->Microsoft.Practices.ObjectBuilder2.BuildFailedException : The current Build operation ...."

1)为什么Unity不使用默认构造函数?

1) Why isn't Unity using the default constructor ?

2)假设我希望Unity使用第二个构造函数(参数化的构造函数),我
如何通过配置将该信息传递给Unity文件?

2) Suppose I want Unity to use the second constructor (the parametized one), How do I pass that information to Unity via the configuration file ?

推荐答案

默认情况下,Unity选择具有最多参数的构造函数。您必须告诉Unity显式使用另一种。

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

一种方法是使用[InjectionConstructor]属性,如下所示:

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.
   }
}

第二种方法,如果您反对杂乱的类/方法与属性,是指定使用 InjectionConstructor

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<Repo>(new InjectionConstructor());

来自文档


Unity如何解析目标构造函数和参数

How Unity Resolves Target Constructors and Parameters

当一个目标类包含多个构造函数时,Unity将使用
一个应用了InjectionConstructor属性的构造函数。如果
有多个构造函数,并且没有一个带有
InjectionConstructor属性,则Unity将使用
参数最多的构造函数。如果有多个这样的构造函数(
比具有相同参数数量的最长构造函数之一多),Unity
将引发异常。

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.

这篇关于Unity不使用类的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆