apolfj
apolfj

Reputation: 960

Microsoft.Unity does not Unity.Resolve<ILogger> when my concrete class has two constructors?

I have a concrete class of logger that Microsoft.Unity will resolve ILogger to.

The logger class has two constructors:

1. public logger()
2. public logger(List<BaseLogger> Loggers)

I have the unity section in my web.config file that looks like this:

<unity>
<containers>
  <container>
    <types>

      <type type="MyCompany.Logger.ILogger, MyCompany.Logger"
           mapTo="MyCompany.Logger.logger, MyCompany.Logger">

      </type>
    </types>
   </container>
  </containers>
</unity>

If I remove the constructor listed as 2, the logger class is successfully resolved by Unity. When I add it back I get this error...

Resolution of the dependency failed, type = "MyCompany.Logger.ILogger", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The type List`1 has multiple constructors of length 1. Unable to disambiguate.

Can anyone explain how I can change my web.config entry to handle having the "2." listed overloaded constructor in logger to work while trying to Unity.Resolve?

Upvotes: 3

Views: 2680

Answers (1)

danish
danish

Reputation: 5600

Unity by default tries to create an instance using the constructor with the maximum number of parameters.

In order to specify which one to use, you need to make use of constructor injection. You can either mark the constructor to be used with InjectionConstructor attribute or specify the constructor in the configuration. This should help.

I understand the documentation on MSDN isn't good enough. See this if it helps. I am not able to find the link to the article I had read today at the office. That had quite good description. Good luck if you can find that one or a better one.

Upvotes: 3

Related Questions