【原文】Dependency Injection in ASP.NET Web API using Autofac
摘要
在ASP.NET Web API里使用Autofac
通過NuGet安裝Autofac.WebApi。(當然要先安裝Autofac.dll)。
PM > Install-Package Autofac.WebApi
引用如下命名空間。
using Autofac;
using Autofac.Integration.WebApi;
再按照如下代碼配置Autofac。
public static class Bootstrapper
{
public static void Run()
{
SetAutofacWebAPI();
}
private static void SetAutofacWebAPI()
{
var configuration = GlobalConfiguration.Configuration;
var builder = new ContainerBuilder();
// Configure the container
builder.ConfigureWebApi(configuration);
// Register API controllers using assembly scanning.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<DefaultCommandBus>().As<ICommandBus>()
.InstancePerApiRequest();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>()
.InstancePerApiRequest();
builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>()
.InstancePerApiRequest();
builder.RegisterAssemblyTypes(typeof(CategoryRepository)
.Assembly).Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerApiRequest();
var services = Assembly.Load("EFMVC.Domain");
builder.RegisterAssemblyTypes(services)
.AsClosedTypesOf(typeof(ICommandHandler<>))
.InstancePerApiRequest();
builder.RegisterAssemblyTypes(services)
.AsClosedTypesOf(typeof(IValidationHandler<>))
.InstancePerApiRequest();
var container = builder.Build();
// Set the WebApi dependency resolver.
var resolver = new AutofacWebApiDependencyResolver(container);
configuration.ServiceResolver.SetResolver(resolver);
}
}
在Application_Start里調用Bootstrapper.Run()。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
//Call Autofac DI configurations
Bootstrapper.Run();
}
Autofac.Mvc4
Autofac ASP.NET MVC integration已經升級到MVC4。 NuGet pacakgeAutofac.Mvc4。它提供了ASP.NET MVC4里的依賴注入(不包括Web API)。Autofac.Mvc3與Autofac.Mvc4沒有什么語法上的不同。
源碼
一個樣例Web程序,用來展示ASP.NET MVC、EF Code First以及架構實踐。
相關資源:
Autofac官網 http://code.google.com/p/autofac/
Autofac ASP.NET MVC3 Ingetation http://code.google.com/p/autofac/wiki/Mvc3Integration