技术总奸

使用Autofac在ASP.NET Web API上实现依赖注入

【原文】Dependency Injection in ASP.NET Web API using Autofac

摘要

在ASP.NET Web API里使用Autofac

通过NuGet安装Autofac.WebApi。(当然要先安装Autofac.dll)。

PM > Install-Package Autofac.WebApi

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.Mvc3Autofac.Mvc4没有什么语法上的不同。

源码

http://efmvc.codeplex.com/ 

一个样例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

posted on 2012-04-03 11:22  阿福  阅读(14243)  评论(1编辑  收藏  举报