KaeL
KaeL

Reputation: 3659

Unity container resolve constructor with no parameter

One of my class has 2 constructors:

public class Foo
{
    public Foo() { }

    public Foo(string bar) { }
}

When I am resolving this from unity, I get an exception because it looks for the string bar parameter. But I want the unity to instantiate this class using the constructor with no parameter. How can I achieve this?

I am using the LoadConfiguration method to register the types from the configuration file.

Unity Container Configuration:

container.LoadConfiguration("containerName");

Config File:

<unity xmlns="">
  <typeAliases>
    <typeAlias alias="string" type="System.String, mscorlib" />
    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
  </typeAliases>
  <containers>
    <container name="containerName">
      <types>
        <type type="IFoo, Assembly"
              mapTo="Foo, Assembly" />
        ...
      </types>
    </container>
  </containers>
</unity>

Upvotes: 1

Views: 1410

Answers (1)

tchelidze
tchelidze

Reputation: 8308

  • [InjectionConstructor] attribute over your constructor specifies which constructor should be used while resolving service

    public class Foo  : IFoo
    {
       [InjectionConstructor]
       public Foo() { }
    
       public Foo(string bar) { }
    }
    

this approach makes you class coupled to Unity, your class becomes less reusable (imagine that you need to use Foo in different scenario where you need to use another constructor) and this way is not recommended , read more about this here

  • Better way is to use API and register you class as follows

    container.RegisterType<IFoo>(new Foo());  
    

Here, you explicitly define how you want your dependency to be resolved.

  • Alternatively you can use Xml Config file, namely specify <contructor> element inside <register> element

Notice that we do not specify <params> child element inside <constructor> element

If no <param> child elements are present, it indicates that the zero-argument constructor should be called

See more about Xml schema here

Upvotes: 3

Related Questions