5

我正在尝试让 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) as 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));

我错过了什么吗?

谢谢

4

4 回答 4

2

您可能想看看这个SO question,其中另一个程序集是从一个引用 API 控制器开始的。

于 2013-03-06T11:13:15.260 回答
2

RegisterApiControllers 注册扩展查找实现IHttpController接口并具有以“Controller”结尾的名称的类型。您的控制器类名称是否有“Controller”后缀?

于 2012-05-03T13:27:39.580 回答
0

您是否忘记使用构建容器为您的 Api 控制器注册构造函数依赖项?

HostingEnvironment.MapPath("~/bin") 是另一种获取 bin 目录中文件路径的好方法。

于 2012-05-03T00:28:02.460 回答
-1
var builder = new ContainerBuilder();   
builder.Update(container);
 var webApiResolver = new Autofac.Integration.WebApi.AutofacWebApiDependencyResolver(container);
    System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
于 2016-06-07T09:34:53.740 回答