加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:13:41 所属栏目:百科 来源:网络整理
导读:1、介绍 所谓程序集级别的依赖注入是指接口和实现的依赖不使用配置文件或硬代码实现 ( builder.RegisterTypeUserInfoService().AsIUserInfoService();),而是通过名称约定实现依赖注入 2、项目接口及dll 2.1 项目结构(创建MVC3项目) 2.2 UI层需引入的dll
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>
/// 使用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)
{
//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;
HomeController(IUserInfoService userService)
{
this .userService = userService;
.AddDisposableObject(userService);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

相关内容
推荐文章
站长推荐
热点阅读