6

错误:

Unity.WebApi.UnityDependencyResolver 类型似乎没有实现 Microsoft.Practices.ServiceLocation.IServiceLocator。

我看到了这个问题WebApi.UnityDependencyResolver does not implement Microsoft.Practices.ServiceLocation.IServiceLocator。参数:commonServiceLocator,但我的错误在这一行:

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

完整的课程:

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;
    }
}

注意:有了这个我得到同样的错误:

    var container = BuildUnityContainer();
    GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
4

1 回答 1

5

ASP.Net MVC 和 Web.API 使用两种不同的依赖解析器基础结构

您的问题是您尝试将Unity.WebApi.UnityDependencyResolver也用于 MVC 控制器。要正确设置统一,请遵循以下说明:

为了使 Unity 与 MVC 控制器一起工作,这些控制器源自Controller

  • 安装Unity.Mvc3 nuget 包
  • 使用以下方法设置dependecy reolver DependencyResolver.SetResolver

    DependencyResolver.SetResolver(
        new Unity.Mvc3.UnityDependencyResolver(container));
    

为了使 Unity 与 Web.API 控制器一起工作,这些控制器派生形式ApiController

  • 安装Unity.WebAPi nuget 包
  • 使用 using 设置依赖解析器GlobalConfiguration.Configuration

    GlobalConfiguration.Configuration.DependencyResolver = 
        new Unity.WebApi.UnityDependencyResolver(container);
    
于 2013-01-28T06:04:16.273 回答