MVC3+AutoFac实现程序集级别的依赖注入
1、介绍
所谓程序集级别的依赖注入是指接口和实现的依赖不使用配置文件或硬代码实现(builder.RegisterType<UserInfoService>().As<IUserInfoService>();),而是通过名称约定实现依赖注入
2、项目接口及dll
2.1 项目结构(创建MVC3项目)

2.2 UI层需引入的dll(使用nuget引入)
2.2.1 Autofac
2.2.2 Autofac.Integration.Mvc
2.2.3 MyMVC3.Business.IServices
2.2.4 MyMVC3.Modules.IRepository
2.2.5 MyMVC3.Modules.Model
3、依赖注入配置代码(在Global.asax的Application_Start方法中调用)
1 2 3 4 5 6 7 8 9 10 11 12 | /// <summary> /// 使用AutoFac实现依赖注入 /// </summary> private void autoFac() { var builder = new ContainerBuilder(); SetupResolveRules(builder); //注入 builder.RegisterControllers(Assembly.GetExecutingAssembly()); //注入所有Controller var container = builder.Build(); DependencyResolver.SetResolver( new AutofacDependencyResolver(container)); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | private void SetupResolveRules(ContainerBuilder builder) { //UI项目只用引用service和repository的接口,不用引用实现的dll。 //如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll var IServices = Assembly.Load( "MyMVC3.Business.IServices" ); var Services = Assembly.Load( "MyMVC3.Business.Services" ); var IRepository = Assembly.Load( "MyMVC3.Modules.IRepository" ); var Repository = Assembly.Load( "MyMVC3.Modules.Repository" ); //根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖 builder.RegisterAssemblyTypes(IServices, Services) .Where(t => t.Name.EndsWith( "Service" )) .AsImplementedInterfaces(); //根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖 builder.RegisterAssemblyTypes(IRepository, Repository) .Where(t => t.Name.EndsWith( "Repository" )) .AsImplementedInterfaces(); } |
4、各层级间配置构造函数注入
4.1 UserInfoService
private IUserInfoRepository productRepository; public UserInfoService(IUserInfoRepository productRepository) { this.productRepository = productRepository; this.AddDisposableObject(productRepository); }
4.2 UserInfoService
1 2 3 4 5 6 7 | public IUserInfoService userService; public HomeController(IUserInfoService userService) { this .userService = userService; this .AddDisposableObject(userService); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2011-04-03 Select语句的处理顺序
2011-04-03 程序出错后,程序员给测试人员的20条高频回复