Error to register Unity in DependencyResolver
asp.net-mvc-4, unity-container
Solution
ASP.Net MVC and Web.API are using two different dependency resolver infrastructure.
Your problem is that you try to use the `Unity.WebApi.UnityDependencyResolver` also for the MVC controllers. To setup unity correctly follow the instructions below:
To make Unity work with MVC controllers the ones which derives from `Controller`
- install the Unity.Mvc3 nuget package
setup the dependecy reolver with using `DependencyResolver.SetResolver`:
DependencyResolver.SetResolver(
new Unity.Mvc3.UnityDependencyResolver(container));
To make Unity work with the Web.API controllers the ones which derives form `ApiController`
- install the Unity.WebAPi nuget package
set the dependency resolver with using `GlobalConfiguration.Configuration`:
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApi.UnityDependencyResolver(container);
Problem
Error: The type Unity.WebApi.UnityDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator. I saw this question WebApi.UnityDependencyResolver does not implement Microsoft.Practices.ServiceLocation.IServiceLocator. Parameter : commonServiceLocator but my error is in this line: ``` DependencyResolver.SetResolver(new UnityDependencyResolver(container)); ``` the complete class: ``` public static class Bootstrapper { public static void Initialise() { var container = BuildUnityContainer(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); // <-- error GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); } private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType<IAutenticacionDbContext, AutenticacionDbContext>(); return container; } } ``` Note: With this I get the same error: ``` var container = BuildUnityContainer(); GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); ```