Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Dear all


I would like to make application with the combination of web api controllers and mvc controllers both I installed following nuget packages
1. unity.mvc4
3. unity.webapi
4. webapi

and I want to impliment dependency injection but I am having problem with dependency resolver
I can call my methods in mvc controller by using Bootstrapper.cs class that is created by default during unity.mvc4 package.
but when i added api controller and try to map my dependency then it is not working
I have searched some solutions as following

http://stackoverflow.com/questions/9527988/cannot-inject-dependencies-into-asp-net-web-api-controller-using-unity[^]


But In above example I am having error on following
C#
System.Web.Http.GlobalConfiguration.Configuration.ServiceResolver.SetResolver

ServiceResolver (red under line not found)

and

C#
private static IUnityContainer BuildUnityContainer()
       {
           var container = new UnityContainer().LoadConfiguration();

           return container;
       }



LoadConfiguration() Not found
I also set unity detail in web.config as per my requiment



XML
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>
    <register type="PersonalShopper.Repositories.IProductListRepository, PersonalShopper.Repositories" mapTo="PersonalShopper.Implementations.MongoRepositories.ProductListRepository, PersonalShopper.Implementations" />
  </container>
</unity>


Please suggest me what I am missing
and please suggest me a sample code for bot mvc controller and web api controller

With regards
Manoj
Posted
Comments
Jameel VM 21-Aug-14 7:47am    
i don't think it is possible because configurations will be different for both web api and mvc. i suggest you to use web api as separate service.
Nathan Minier 22-Aug-14 9:27am    
Make sure that you have System.Web.Mvc referenced (it's not in a WebAPI app) and make sure to set you Unity resolver first in your Global.asax.cs. Also, you likely need a custom controller factory:

public void Application_Start()
{
DependencyResolver.SetResolver(new UnityResolver());

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

// everything else
}

After that, keep in mind that the ApiController is IHttpController and the MVC Controller is IController, if you're injecting via contract. You'll need to distinguish the two in the controller factory.

WebAPI and MVC are similar, but don't natively play nice. It'll just take a little legwork to get the DI to understand the difference between the two.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900