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

前端之家收集整理的这篇文章主要介绍了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.3MyMVC3.Business.IServices
2.2.4MyMVC3.Modules.IRepository
2.2.5MyMVC3.Modules.Model
3、依赖注入配置代码(在Global.asax的Application_Start方法调用
1
2
3
4
5
6
7
8
9
10
11
12
/// <summary>
@H_502_118@ /// 使用AutoFac实现依赖注入
/// </summary>
private void autoFac()
{
var builder = new ContainerBuilder();
SetupResolveRules(builder); //注入
builder.RegisterControllers(Assembly.GetExecutingAssembly()); //注入所有Controller
container = builder.Build();
DependencyResolver.SetResolver( AutofacDependencyResolver(container));
}

  

12
13
14
15
16
17
18
19
SetupResolveRules(ContainerBuilder builder)
@H_502_118@ {
//UI项目只用引用service和repository的接口,不用引用实现的dll。
//如需加载实现的程序集,将dll拷贝到bin目录下即可,不用引用dll
IServices = Assembly.Load( "MyMVC3.Business.IServices" );
Services = Assembly.Load( "MyMVC3.Business.Services" );
IRepository = Assembly.Load( "MyMVC3.Modules.IRepository" );
Repository = Assembly.Load( "MyMVC3.Modules.Repository" );
//根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖
builder.RegisterAssemblyTypes(IServices,Services)
.Where(t => t.Name.EndsWith( "Service" ))
.AsImplementedInterfaces();
//根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖
builder.RegisterAssemblyTypes(IRepository,Repository)
"Repository" ))
.AsImplementedInterfaces();
4、各层级间配置构造函数注入
4.1 UserInfoService
 private IUserInfoRepository productRepository;
        public UserInfoService(IUserInfoRepository productRepository)
        {
            this.productRepository = productRepository;
            this.AddDisposableObject(productRepository);
        }

4.2 UserInfoService
7
public IUserInfoService userService;
@H_502_118@
HomeController(IUserInfoService userService)
{
this .userService = userService;
.AddDisposableObject(userService);
}

猜你在找的设计模式相关文章