5

I'm trying to get Autofac to work with WebApi. I have my ApiControllers in a separate project from the main web project.

InventorySystem.Web.UI InventorySystem.Web.Api.Controllers

Whenever i try to browse to an api route i get the response:

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

When i step through the Autofac code I see that my controller has been registered, but the AutofacControllerActivator.Create() returns null. Specifically the line return (ResolutionExtensions.ResolveOptional(scope, controllerType) as IHttpController);

The autofac code: 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));

Am i missing something?

Thanks

4

4 に答える 4

2

RegisterApiControllers 登録拡張機能は、IHttpControllerインターフェイスを実装し、"Controller" で終わる名前を持つ型を探します。コントローラーのクラス名に「Controller」という接尾辞が付いていますか?

于 2012-05-03T13:27:39.580 に答える
2

このSO questionを見てみることをお勧めします。他のアセンブリは、参照 API コントローラーの 1 つから開始されます。

于 2013-03-06T11:13:15.260 に答える
0

Api コントローラーのコンストラクターの依存関係をビルド コンテナーに登録するのを忘れていませんか?

HostingEnvironment.MapPath("~/bin") は、bin ディレクトリ内のファイルへのパスを取得する別の良い方法です。

于 2012-05-03T00:28:02.460 に答える