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

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

  

 

你可能感兴趣的:(MVC3+AutoFac实现程序集级别的依赖注入)