gpt4 book ai didi

c# - ASP.Net MVC 4 Web API Controller 不适用于 Unity.WebApi

转载 作者:可可西里 更新时间:2023-11-01 08:53:46 24 4
gpt4 key购买 nike

我的 ASP.Net MVC 4 Web API Controller 不支持 Unity.WebApi。在同一个项目中,简单的 Controller 可以正确地与 Unity.Mvc3 配合使用。但是当我运行从 ApiController 派生的 Web API Controller 时,我收到一条消息:

{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"Type 'ElectricTests.Controllers.Api.DocumentsController' does not have a default constructor","ExceptionType":"System.ArgumentException","StackTrace":" at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}

我的 API Controller :

public class DocumentsController : ApiController
{
private readonly IDocumentsRepository _repository;

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

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

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 的处理方式不同,因为它们具有完全不同的基类:

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

Install-Package Unity.MVC4

和用于 DI 的 Unity.WebAPI ( http://www.nuget.org/packages/Unity.WebAPI/ )

Install-Package Unity.WebAPI

你的 Bootstrap 应该是两者的结合:

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

请注意,我还必须添加一些注册才能使帮助页面正常工作

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

作为 Unity.MVC4 的所有者,我希望在我们的库中实现 WebApi。

关于c# - ASP.Net MVC 4 Web API Controller 不适用于 Unity.WebApi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16130020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com