本文介绍了ASP.Net MVC 4 Web API控制器不适用于Unity.WebApi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 derived from ApiController I'm getting a message:

我的ApiController:

My ApiController:

public class DocumentsController : ApiController
{
    private readonly IDocumentsRepository _repository;

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

    public IEnumerable<FormattedDocument> GetFormattedDocuments()
    {
        return _repository.GetAllFormattedDocuments();
    }
    ...

Bootstrapper.cs:

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

我的错误在哪里?

推荐答案

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

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

我将Unity.MVC4库用于控制器DI( http://www.nuget.org /packages/Unity.MVC4/)

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

Install-Package Unity.MVC4

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

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

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

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

这篇关于ASP.Net MVC 4 Web API控制器不适用于Unity.WebApi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:01