2012-02-26 62 views
9

我一直在使用autofac和MVC 3一段時間並喜歡它。我最近將一個項目升級到了MVC 4,除了Web API ApiControllers之外,似乎所有東西都可以工作。我收到以下例外情況。Autofac和ASP.NET Web API ApiController

An error occurred when trying to create a controller of type 'MyNamespace.Foo.CustomApiController'. Make sure that the controller has a parameterless public constructor. 

在我看來,這似乎是DI通過autofac的一個問題。我是否錯過了某些東西或者是否有某些東西在作品中。我知道,MVC4剛剛出來,是一個測試版,所以我不期望太多,但認爲我可能會錯過一些東西。

回答

10

我已經在NuGet上爲MVC 4和Web API的Beta版本發佈了Autofac集成包。該集成將爲每個控制器請求(MVC控制器或API控制器根據集成)創建一個Autofac生命週期範圍。這意味着控制器及其依賴關係將在每次通話結束時自動處理。這兩個軟件包可以並排安裝在同一個項目中。

MVC 4

https://nuget.org/packages/Autofac.Mvc4

http://alexmg.com/post/2012/03/09/Autofac-ASPNET-MVC-4-(Beta)-Integration.aspx

的Web API

https://nuget.org/packages/Autofac.WebApi/

http://alexmg.com/post/2012/03/09/Autofac-ASPNET-Web-API-(Beta)-Integration.aspx

鏈接現在已修復。

+1

不幸的是,就這個評論的打字而言,似乎同時使用Autofac for MVC 4 RC和Web API RC不起作用。我收到有關在Web API框架程序集中找不到的類型的編譯器警告。我不得不使用@tugberk提供的答案,並重新實現依賴解析器來解決它。 – NathanAldenSr 2012-09-07 01:24:41

4

我剛剛在我的一個應用程序上配置了它。這樣做有它不同的方式,但我喜歡這種方法:

Autofac and ASP.NET Web API System.Web.Http.Services.IDependencyResolver Integration

首先,我創建了一個實現System.Web.Http.Services.IDependencyResolver接口的類。

internal class AutofacWebAPIDependencyResolver : System.Web.Http.Services.IDependencyResolver { 

    private readonly IContainer _container; 

    public AutofacWebAPIDependencyResolver(IContainer container) { 

     _container = container; 
    } 

    public object GetService(Type serviceType) { 

     return _container.IsRegistered(serviceType) ? _container.Resolve(serviceType) : null; 
    } 

    public IEnumerable<object> GetServices(Type serviceType) { 

     Type enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType); 
     object instance = _container.Resolve(enumerableServiceType); 
     return ((IEnumerable)instance).Cast<object>(); 
    } 
} 

我還有另一類認爲我登記:

internal class AutofacWebAPI { 

    public static void Initialize() { 
     var builder = new ContainerBuilder(); 
     GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
      new AutofacWebAPIDependencyResolver(RegisterServices(builder)) 
     ); 
    } 

    private static IContainer RegisterServices(ContainerBuilder builder) { 

     builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).PropertiesAutowired(); 

     builder.RegisterType<WordRepository>().As<IWordRepository>(); 
     builder.RegisterType<MeaningRepository>().As<IMeaningRepository>(); 

     return 
      builder.Build(); 
    } 
} 

然後,在Application_Start初始化:

protected void Application_Start() { 

    //... 

    AutofacWebAPI.Initialize(); 

    //... 
} 

我希望這有助於。