Skip to content

ASP.NET classic WebApi 中使用 Autofac 依赖注入容器

🏷️ ASP.NET Autofac

ASP.NET classic MVC 项目中使用 Autofac 来实现依赖注入,但是在调用 ApiController 中的 API 时总是返回如下错误消息:

json
{
  "Message": "出现错误。"
}

由于没有具体的错误信息,调查了好久才发现是 ApiController 的构造函数中的依赖注入导致的。

没想到 ControllerApiController 的依赖注入解析是分开的,而且配置方式也有一些不同。

ASP.NET classic MVC

ASP.NET classic MVC 中使用 Autofac 是需要安装 Autofac.Mvc5 包,示例如下:

csharp
protected void Application_Start()
{
  var builder = new ContainerBuilder();

  // Register your MVC controllers. (MvcApplication is the name of
  // the class in Global.asax.)
  builder.RegisterControllers(typeof(MvcApplication).Assembly);

  // OPTIONAL: Register model binders that require DI.
  builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
  builder.RegisterModelBinderProvider();

  // OPTIONAL: Register web abstractions like HttpContextBase.
  builder.RegisterModule<AutofacWebTypesModule>();

  // OPTIONAL: Enable property injection in view pages.
  builder.RegisterSource(new ViewRegistrationSource());

  // OPTIONAL: Enable property injection into action filters.
  builder.RegisterFilterProvider();

  // OPTIONAL: Enable action method parameter injection (RARE).
  builder.InjectActionInvoker();

  // Set the dependency resolver to be Autofac.
  var container = builder.Build();
  DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

ASP.NET classic WebApi

ASP.NET classic WebApi 中使用时则需要安装 Autofac.WebApi2Autofac.WebApi 包,示例如下:

csharp
protected void Application_Start()
{
  var builder = new ContainerBuilder();

  // Get your HttpConfiguration.
  var config = GlobalConfiguration.Configuration;

  // Register your Web API controllers.
  builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

  // OPTIONAL: Register the Autofac filter provider.
  builder.RegisterWebApiFilterProvider(config);

  // OPTIONAL: Register the Autofac model binder provider.
  builder.RegisterWebApiModelBinderProvider();

  // Set the dependency resolver to be Autofac.
  var container = builder.Build();
  config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}

更多相关内容可以参考官方文档:MVCWeb API