ASP.Net MVC 4 Web API controller doesn't work with Unity.WebApi

前端 未结 2 1068
温柔的废话
温柔的废话 2020-12-17 19:28

My ASP.Net MVC 4 Web API controller doesn\'t work with Unity.WebApi. In the same project simple controllers works with Unity.Mvc3 properly. But when I run Web API controller

相关标签:
2条回答
  • 2020-12-17 19:51

    When you install Unity for ASP.NET Web API, it does everything except add the following line to your Global.asax

    Bootstrapper.Initialise();
    

    So you need to add that to your Application_Start method:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        Bootstrapper.Initialise();
    
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
    
    0 讨论(0)
  • 2020-12-17 19:54

    The handling of Controller and ApiController is different as they have completely different base classes:

    I use Unity.MVC4 library for controller DI (http://www.nuget.org/packages/Unity.MVC4/)

    Install-Package Unity.MVC4
    

    and Unity.WebAPI for DI (http://www.nuget.org/packages/Unity.WebAPI/)

    Install-Package Unity.WebAPI
    

    Your bootstrapper should be a combination of both:

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

    Note I also had to do to add some registration to get the Help page to work

    container.RegisterInstance(typeof (HttpConfiguration), GlobalConfiguration.Configuration);
    

    As the owner of Unity.MVC4 I am looking at getting WebApi implemented within our library.

    0 讨论(0)
提交回复
热议问题