Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure unity container to provide string constructor value?

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

like image 309
iAteABug_And_iLiked_it Avatar asked Jun 30 '13 14:06

iAteABug_And_iLiked_it


People also ask

How do I register a type with Unity container?

Before Unity resolves the dependencies, we need to register the type-mapping with the container, so that it can create the correct object for the given type. Use the RegisterType() method to register a type mapping. Basically, it configures which class to instantiate for which interface or base class.

What is Injectionfactory?

A class that lets you specify a factory method the container will use to create the object.

What is Injectionconstructor?

A class that holds the collection of information for a constructor, so that the container can be configured to call this constructor.


1 Answers

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>
like image 179
p.s.w.g Avatar answered Sep 25 '22 04:09

p.s.w.g