WebApi.UnityDependencyResolver does not implement Microsoft.Practices.ServiceLocation.IServiceLocator. Parameter: commonServiceLocator

I am trying to run the following code:

using System.Web.Http; using System.Web.Mvc; using Conduit.Mam.ClientSerivces.Dal.Configuration; using MamInfrastructure.Common.Dal; using MamInfrastructure.Common.Logger; using MamInfrastructure.Logger; using Microsoft.Practices.Unity; using Unity.WebApi; namespace Conduit.Mam.ClientServices.Common.Initizliaer { public static class Initializer { private static bool isInitialize; private static readonly object LockObj = new object(); private static IUnityContainer defaultContainer = new UnityContainer(); static Initializer() { Initialize(); } public static void Initialize() { if (isInitialize) return; lock (LockObj) { IUnityContainer container = defaultContainer; //registering Unity for web API GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); //registering Unity for MVC DependencyResolver.SetResolver(new UnityDependencyResolver(container)); container.RegisterType<IDal<ClientService.DAL.EntityFramework.MamConfiguration>, MamConfigurationDal>(); container.RegisterType<IApplicationLogger, Log4NetLogger>(); if (!isInitialize) { isInitialize = true; } } } } } 

ad get the following exception:

The type Unity.WebApi.UnityDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator. Parameter name: commonServiceLocator

I tried installing the webApi package but it did not help

+6
source share
2 answers

In your Initialize method, replace:

 GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); 

with:

 GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); 

Now you understand what the problem is:

System.Web.Http.Dependencies.IDependencyResolver (using the web API) and System.web.Mvc.IDependencyResolver (using ASP.NET MVC) are two completely different types (even if they have the same name), but with In this, you are trying to assign both of them to the same type ( UnityDependencyResolver ), which obviously cannot work.

+21
source

I had a similar problem, but in my case my web application has MVC and WebApi Controllers. I decided like this:

 using Microsoft.Practices.Unity; using System.Web.Http; using System.Web.Mvc; using Unity.Mvc5; DependencyResolver.SetResolver(new UnityDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); 

If the first line will use MVC DependencyResolver, and in the second line I use WebApi UnityDependencyResolver.

+7
source

All Articles