2014-01-12 55 views
4

我剛更新了所有Autofac包到最新版本以獲得對web api 2的支持。在我的api控制器中,我建立了一個構造函數,要求提供一個服務層類的實例,這是相同的到我如何使用autofac與我所有的mvc控制器,它工作正常。AutoFac Web Api 2集成問題

在我的應用程序啓動時執行的ioc配置中,我註冊了web api控制器。

builder.RegisterType<UsersApiController>().InstancePerApiRequest(); 

我也試過

builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 

但autofac沒有與我的API控制器工作時,一個詢問被注入了服務類甚至沒有得到執行的構造。如果我在api控制器上不包含默認參數少構造函數,我也會得到一個錯誤。

是否有一個已知的問題與web api 2和汽車fac還是我錯過了什麼?

+2

你有沒有設置'GlobalConfiguration.Configuration.DependencyResolver'? – nemesv

+0

是什麼? DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); – JBeckton

+0

我的mvc控制器按照DI的預期工作,想知道爲什麼API控制器不是。 – JBeckton

回答

-1

此博客爲我工作

http://danielhindrikes.se/cloud/azure/azure-mobile-services-and-autofac/

所以我的代碼現在看起來是

public static void Register(){ 

      ConfigOptions options = new ConfigOptions(); 

      //Prepare Dependency Injection Container 
      var configBuilder = new ConfigBuilder(options, DependencyInjectionConfig); 


      // Use this class to set WebAPI configuration options 
      HttpConfiguration config = ServiceConfig.Initialize(configBuilder); 
} 

private static void DependencyInjectionConfig(ContainerBuilder containerBuilder) 
{ 
      containerBuilder.Register(component => new EFProductRepository()).As<IProductRepository>().SingleInstance(); 
      containerBuilder.RegisterType<ProductsManager>().As<IProductsManager>(); 
}