技术总奸

< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

统计

使用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   阿福  阅读(14249)  评论(1)    收藏  举报

编辑推荐:
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· 通过一个DEMO理解MCP(模型上下文协议)的生命周期
· MySQL下200GB大表备份,利用传输表空间解决停服发版表备份问题
· 记一次 .NET某固高运动卡测试 卡慢分析
· 微服务架构学习与思考:微服务拆分的原则
阅读排行:
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· .NET周刊【3月第5期 2025-03-30】
· 即时通信SSE和WebSocket对比
· .net clr 8年才修复的BUG,你让我损失太多了
· 一个神奇的JS代码,让浏览器在新的空白标签页运行我们 HTML 代码(createObjectURL
点击右上角即可分享
微信分享提示