如何配置的统一容器提供的字符串构造的价值? [英] How to configure unity container to provide string constructor value?

查看:205
本文介绍了如何配置的统一容器提供的字符串构造的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 的父亲

 公共类爸
{
公共字符串名称
{
获得;设置;
}
公共爸爸(字符串名称)
{
名称=名称;
}
}

这是我的测试方法



 公共无效TestDad()
{
UnityContainer DadContainer =新UnityContainer();
爸newdad = DadContainer.Resolve<&爸爸GT;();
newdad.Name =克里斯
Assert.AreEqual(newdad.Name,克里斯);
}

这是我收到


$错误b $ b

 出现InvalidOperationException  -  String类型无法构造
必须配置为提供此值的容器。

如何配置我的 DadContainer 这个论断通过?
谢谢


解决方案

您应该提供一个无参数的构造函数:

 公共类爸
{
公共字符串名称{;组; }

公共爸爸()
{
}

公共爸爸(字符串名称)
{
名称=名称;
}
}

如果你不能提供一个参数的构造函数,你需要在容器配置提供它,无论是通过与容器直接注册的:

  UnityContainer DadContainer =新UnityContainer(); 
DadContainer.RegisterType<&爸爸GT;(
新InjectionConstructor(克里斯));

或通过应用程序/ web.config文件:



<预类=郎咸平的XML prettyprint-覆盖> < configSections>
<节名称=团结TYPE =Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration/>
< / configSections>

<统一>
<集装箱>
<集装箱>
<注册类型=System.String,MyProject的>
<&构造GT;
< PARAM NAME =名字值=克里斯/>
< /构造>
< /注册>
< /容器>
< /箱>
< /统一性GT;


This is my dad class

 public class Dad
    {
        public string Name
        {
            get;set;
        }
        public Dad(string name)
        {
            Name = name;
        }
    }

This is my test method

public void TestDad()
        {
           UnityContainer DadContainer= new UnityContainer();
           Dad newdad = DadContainer.Resolve<Dad>();    
           newdad.Name = "chris";    
           Assert.AreEqual(newdad.Name,"chris");                 
        }

This is the error I am getting

"InvalidOperationException - the type String cannot be constructed.
 You must configure the container to supply this value"

How do I configure my DadContainer for this assertion to pass? Thank you

解决方案

You should provide a parameterless constructor:

public class Dad
{
    public string Name { get; set; }

    public Dad()
    {
    }

    public Dad(string name)
    {
        Name = name;
    }
}

If you can't provide a parameterless constructor, you need to configure the container to provide it, either by directly registering it with the container:

UnityContainer DadContainer = new UnityContainer();
DadContainer.RegisterType<Dad>(
    new InjectionConstructor("chris"));

or through the app/web.config file:

<configSections>
  <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>

<unity>
  <containers>
    <container>
      <register type="System.String, MyProject">
        <constructor>
          <param name="name" value="chris" />
        </constructor>
      </register >
    </container>
  </containers>
</unity>

这篇关于如何配置的统一容器提供的字符串构造的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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