我正在努力让Autofac与WebApi合作。我将ApiControllers放在与主Web项目不同的项目中。
InventorySystem.Web.UI InventorySystem.Web.Api.Controllers
每当我尝试浏览api路线时,我都会收到回复:
<Exception xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ExceptionType>System.ArgumentNullException</ExceptionType>
<Message>Value cannot be null. Parameter name: value</Message>
<StackTrace>
at System.Web.Http.Controllers.HttpControllerContext.set_Controller(IHttpController value)
at System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateInstance(HttpControllerContext controllerContext, HttpControllerDescriptor controllerDescriptor)
at System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateController(HttpControllerContext controllerContext, String controllerName)
at Autofac.Integration.WebApi.AutofacControllerFactory.CreateController(HttpControllerContext controllerContext, String controllerName)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
</StackTrace>
</Exception>
当我单步执行Autofac代码时,我看到我的控制器已经注册,但AutofacControllerActivator.Create()返回null。特别是这条线 return(ResolutionExtensions.ResolveOptional(scope,controllerType)为IHttpController);
autofac代码: string binDirectory = Path.Combine(HttpRuntime.AppDomainAppPath,“bin”);
var builder = new ContainerBuilder();
builder.ConfigureWebApi(GlobalConfiguration.Configuration);
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
builder.RegisterApiControllers(Assembly.LoadFile(Path.Combine(binDirectory, "InventorySystem.Web.Api.dll"))).PropertiesAutowired();
builder.RegisterFilterProvider();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new AutofacWebApiDependencyResolver(container));
我错过了什么吗?
由于
答案 0 :(得分:2)
RegisterApiControllers注册扩展查找实现IHttpController
接口并且名称以“Controller”结尾的类型。您的控制器类名称后缀为“Controller”吗?
答案 1 :(得分:2)
您可能需要查看此SO question,其中其他程序集从其中一个引用API控制器开始接收。
答案 2 :(得分:0)
您是否忘记使用构建容器注册Api控制器的构造函数依赖项?
HostingEnvironment.MapPath(“〜/ bin”)是另一种获取bin目录中文件路径的好方法。
答案 3 :(得分:-1)
var builder = new ContainerBuilder();
builder.Update(container);
var webApiResolver = new Autofac.Integration.WebApi.AutofacWebApiDependencyResolver(container);
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;