ASP.Net MVC 4 Web API控制器不能与Unity.WebApi一起使用
我的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 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 // eg container.RegisterType(); container.RegisterType(); container.RegisterType(); container.RegisterType(); return container; } }
我的错误在哪里?
Controller和ApiController的处理方式不同,因为它们具有完全不同的基类:
我将Unity.MVC4库用于控制器DI( https://www.nuget.org/packages/Unity.MVC4/ )
Install-Package Unity.MVC4
和Unity.WebAPI for DI( https://www.nuget.org/packages/Unity.WebAPI/ )
Install-Package Unity.WebAPI
你的引导程序应该是两者的组合:
DependencyResolver.SetResolver(new Unity.Mvc4.UnityDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
注意我还需要添加一些注册以使“帮助”页面起作用
container.RegisterInstance(typeof (HttpConfiguration), GlobalConfiguration.Configuration);
作为Unity.MVC4的所有者,我正在寻找在我们的库中实现WebApi。
安装Unity for ASP.NET Web API时,除了将以下行添加到Global.asax之外,它会执行所有操作
Bootstrapper.Initialise();
所以你需要将它添加到Application_Start方法:
上述就是C#学习教程:ASP.Net MVC 4 Web API控制器不能与Unity.WebApi一起使用分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); Bootstrapper.Initialise(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1012139.html