C# 如何配置统一容器以提供字符串构造函数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17391122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:23:43  来源:igfitidea点击:

How to configure unity container to provide string constructor value?

c#visual-studio-2010dependency-injectioninversion-of-controlunity-container

提问by iAteABug_And_iLiked_it

This is my dadclass

这是我的dad

 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 DadContainerfor this assertion to pass? Thank you

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

采纳答案by p.s.w.g

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:

或通过 app/web.config 文件:

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