MVC3+AutoFac实现程序集级别的依赖注入

本文介绍了一种程序集级别的依赖注入方法,通过名称约定而非配置文件实现依赖注入,使用Autofac框架完成MVC项目的依赖配置,并展示了如何通过构造函数注入实现各层级间的依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
      }

  

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值