zosim
zosim

Reputation: 2979

Unity 3: The type does not have an accessible constructor

I have a following interface and implementation

namespace ProjectName.Web
{
    public interface IWebUtil
    {        
    }
}


namespace ProjectName.Web
{
    public class WebUtil : IWebUtil
    {                
    }
}

in my config i have this registration. I am using Unity 3.

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <assembly name="ProjectName.Web" />
  ...
   <register name="WebUtil" type="ProjectName.Web.IWebUtil" mapTo="ProjectName.Web.WebUtil">
     <lifetime type="transient" />    
   </register>
  ...

When I try to resolve this configuration I am getting this error:

Exception is: InvalidOperationException - The type IWebUtil does not have an accessible       constructor.
-----------------------------------------------
At the time of the exception, the container was:
Resolving ProjectName.Web.IWebUtil,(none)

I have tried to add empty public constructor but no sucess.

Can anybody help with this? thanks.

Upvotes: 1

Views: 12628

Answers (1)

Randy Levy
Randy Levy

Reputation: 22655

The first step is to ensure that you are loading the Unity configuration since this is not done by default. To do this:

using Microsoft.Practices.Unity.Configuration;

container.LoadConfiguration();

I'm assuming you've done this. I'm also going to assume that you are trying to resolve IWebUtil using the following code:

container.Resolve<IWebUtil>();

This throws an InvalidOperationException because IWebUtil is configured as a named registration (with name "WebUtil"). So either resolve using the configured name:

container.Resolve<IWebUtil>("WebUtil");

Or change the registration to be a default (unnamed) registration:

<register name="" type="ProjectName.Web.IWebUtil" mapTo="ProjectName.Web.WebUtil">
 <lifetime type="transient" />    
</register>

Upvotes: 2

Related Questions