ASP.Net MVC 4 Web API控制器不适用于Unity.WebApi

Obl*_*ngo 10 c# asp.net api json unity-container

我的ASP.Net MVC 4 Web API控制器不适用于Unity.WebApi.在同一个项目中,简单的控制器可以正常使用Unity.Mvc3.但是,当我运行从ApiController派生的Web API控制器时,我收到一条消息:

{"$ id":"1","Message":"发生错误.","ExceptionMessage":"类型'ElectricTests.Controllers.Api.DocumentsController'没有默认构造函数","ExceptionType":" System.Web.Http.Internal.TypeActivator.Create [TBase](Type instanceType)\ r \"System.Linq.Expressions.Expression.New(Type type)\ r \n的System.ArgumentException","StackTrace":" n在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage请求,类型controllerType,Func`1和激活器)\ r \n在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType) )"}

我的ApiController:

public class DocumentsController : ApiController
{
    private readonly IDocumentsRepository _repository;

    public DocumentsController(IDocumentsRepository repository) {
        _repository = repository;
    }

    public IEnumerable<FormattedDocument> GetFormattedDocuments()
    {
        return _repository.GetAllFormattedDocuments();
    }
    ...
Run Code Online (Sandbox Code Playgroud)

Bootstrapper.cs:

public static class Bootstrapper {
    public static void Initialise() {
        IUnityContainer container = BuildUnityContainer();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    private static IUnityContainer BuildUnityContainer() {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers
        // e.g. container.RegisterType<ITestService, TestService>();            

        container.RegisterType<IDocumentsRepository, DocumentsRepository>();
        container.RegisterType<IQuestionsRepository, QuestionsRepository>();
        container.RegisterType<ITestRepository, TestsRepository>();

        return container;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的错误在哪里?

Oli*_*ver 28

Controller和ApiController的处理方式不同,因为它们具有完全不同的基类:

我使用Unity.MVC4库作为控制器DI(http://www.nuget.org/packages/Unity.MVC4/)

Install-Package Unity.MVC4
Run Code Online (Sandbox Code Playgroud)

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

Install-Package Unity.WebAPI
Run Code Online (Sandbox Code Playgroud)

你的引导程序应该是两者的组合:

DependencyResolver.SetResolver(new Unity.Mvc4.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
Run Code Online (Sandbox Code Playgroud)

注意我还需要添加一些注册以使"帮助"页面起作用

container.RegisterInstance(typeof (HttpConfiguration), GlobalConfiguration.Configuration);
Run Code Online (Sandbox Code Playgroud)

作为Unity.MVC4的所有者,我正在寻找在我们的库中实现WebApi.