初始化Web API控制器时如何配置autofac以为接口注入类型?

时间:2013-03-14 10:15:01

标签: asp.net-mvc asp.net-web-api inversion-of-control autofac

我有一个WebAPI控制器,它依赖于另一个类:

 public class HealthCheckController : System.Web.Http.ApiController
    {
        private readonly IHealthCheckReport _healthCheckReport;

        public HealthCheckController(IHealthCheckReport healthCheckReport)
        {
            this._healthCheckReport = healthCheckReport;
        }
}

我正在使用Autofac并在我的WebApiConfig类的Register方法中,我添加了:

 var builder = new ContainerBuilder();
 builder.RegisterType<HealthCheckReport>().As<IHealthCheckReport>();
 var container = builder.Build();

 // Set the dependency resolver for Web API.
 var webApiResolver = new AutofacWebApiDependencyResolver(container);
 GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

但是当我调用Index()动作时,它会抱怨我的控制器没有默认构造函数。然而,我预计Autofac会神奇地注入我上面注册的类型。

应如何配置?

1 个答案:

答案 0 :(得分:2)

您也需要注册api控制器。

  builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

来源:http://code.google.com/p/autofac/wiki/WebApiIntegration