1
votes

I'm trying to configure Unity IoC in ASP.NET Web Api project. I have made installation of Unity.WebAPI package:

PM > Install-Package Unity.MVC4

And added the next code to Initialise method of Bootstrapper class:

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

Also I have registered my repository in container:

container.RegisterType<IProductRepository, ProductRepository>();

But my App crashes with the error Type 'MvcApplication1.Controllers.ValuesController' does not have a default constructor. Could someone point me out what have I missed? I use .Net Framework 4.5. Which package of Unity is OK for my purposes (Unity.WebAPI, Unity.MVC4, ...)?

Updated: Injection of repository into controller:

private readonly IProductRepository _repository;

public ValuesController(IProductRepository repository)
{
    _repository = repository;
}
2
i think you should add your code of ValuesController as well as it seems the error is in conjunction with that, what methods are there inside that controller, which one did you (try to) call? - DrCopyPaste
Oops! I'm sorry, just updated. - alex.mironov
wait a second! First you say I have made installation of Unity.WebAPI, but then you install Unity.MVC4 which one was it now, what are you building? MVC application or Web API application? - DrCopyPaste
I'm working on Web API project, but installed package is Unity.MVC4. Actually I've tried to install Unity.WebAPI but after installation I found compile errors: 'MvcApplication1.Areas.HelpPage.XmlDocumentationProvider' does not implement interface member 'System.Web.Http.Description.IDocumentationProvider.GetResponseDocumentation(System.Web.Http.Controllers.HttpActionDescriptor)' ...\MvcApplication1\Areas\HelpPage\XmlDocumentationProvider.cs As a result I have no idea how to workaround it... - alex.mironov
did you try what i suggested you in my answer? - DrCopyPaste

2 Answers

1
votes

What you did looks good so far, but I think you are missing just this one line

Bootstrapper.Initialise();

This should go into the startup code of your application Global.asax.cs for MVC-Applications for example, just put it there at the end inside of this method

protected void Application_Start()
0
votes

Probably you are following this article. If not, it could help you out.

http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver

Regarding the error, try adding a constructor to the controller with no parameters:

i.e.

public ValuesController()
{

}