这基本上是为 mvc 配置 Autofac 的最少代码量。你需要引用 Autofac.Integration.Mvc,如果你使用 webapi,你也需要引用 Autofac.Integration.Webapi。
public static class AutofacConfig
{
public static IContainer Register()
{
var assembly = typeof(MvcApplication).Assembly;
var builder = new ContainerBuilder();
builder.RegisterControllers(assembly);
// If you don't need webapi, you can omit this, else you need Autofac.Integration.Webapi
builder.RegisterApiControllers(assembly);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// If you don't need webapi, you can omit this, else you need Autofac.Integration.Webapi
var resolver = new AutofacWebApiDependencyResolver(container);
// Configure Web API with the dependency resolver.
GlobalConfiguration.Configuration.DependencyResolver = resolver;
return container;
}
}
然后在 Global.Asax 中添加
AutofacConfig.Register();
在 Application_Start 方法中作为第一个调用之一。