17

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

iAteABug_And_iLiked_it
  • 3,725
  • 9
  • 36
  • 75

1 Answers1

28

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>
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • its as simple as that? LOL ... but what if I can't and the constructor must have a string parameter?( for some reason that I can't think of right now) – iAteABug_And_iLiked_it Jun 30 '13 at 14:06
  • This does not answer the question. – user1908061 Jun 30 '13 at 14:14
  • 10
    You can definitely use an `InjectionConstructor` to supply the name. However, that will always use the same name for all `Dad` instances. If you want a different value you can use a ResolverOverride: `DadContainer.Resolve(new ParameterOverride("name", nameOfDad));` – Randy Levy Jun 30 '13 at 14:43