service 层注入不同的数据源_.NET 理论基础+实战控制台程序实现AutoFac注入

(给DotNet加星标,提升.Net技能)

转自:在7楼 

cnblogs.com/RayWang/p/11128554.html

简介

该系列共5篇文章,旨在以实战模式,在.NET下的

  • 控制台程序

  • Framework Mvc程序

  • Framework WebApi程序

  • Core Api程序

分别实现依赖注入。

其中.NET  Framework框架主要以如何引入AutoFac作为容器以及如何运用AuotoFac为主,.NET Core框架除了研究引入AutoFac的两种方式,同时也运用反射技巧对其自带的DI框架进行了初步封装,实现了相同的依赖注入效果。

项目架构如下图:

6482263991c1d2d4ac43ff4157be78f1.png

265269f4723dd0305539677fa6e0b1d9.png

GitHub源码地址:https://github.com/WangRui321/Ray.EssayNotes.AutoFac

适用对象

该项目主要实战为主,理论部分我会结合例子和代码,深入浅出地阐述,如果你是:

  • 从来没听过IoC、DI这些劳什子

  • 了解一些依赖注入的理论知识但是缺乏实战

  • 在.Net Framework下已熟练运用依赖注入,但在.NET Core还比较陌生

只要你花上半个小时认真读完每一句话,我有信心这篇文章一定会对你有所帮助。

如果你是:

  • 发量比我还少的秒天秒地的大牛

那么也欢迎阅读,虽然可能对你帮助并不大,但是欢迎提供宝贵的意见,有写的不好的地方可以互相交流~

理论基础

依赖

依赖,简单说就是,当一个类需要另一个类协作来完成工作的时候就产生了依赖。这也是耦合的一种形式。

举个例子,比如标准的三层架构模式

d594a50c309df657949e56f8eed11b86.png

数据访问层(DAL)代码:

/// 
/// 学生仓储
///
public class StudentRepository
{
public string GetName(long id){
return "学生张三";//造个假数据返回
}
}

业务层(BLL)代码:

/// 
/// 学生逻辑处理
///
public class StudentService
{
private readonly StudentRepository _studentRepository;
public StudentService(){
_studentRepository = new StudentRepository();
}
public string GetStuName(long id){
var stu = _studentRepository.Get(id);
return stu.Name;
}
}

其中,StudentService的实现,就必须要依赖于StudentRepository。而且这是一种紧耦合,一旦StudentRepository有任何更改,必然导致StudentService的代码同样也需要更改,这种情况是程序员们不愿意看到的。

接口驱动

接口驱动是为了实现一个设计原则:要依赖于抽象,而不是具体的实现。

还拿上面的例子说明,现在我添加一个DAL的接口层,IStudentRepository,抽象出所需方法:

/// 
/// 学生仓储interface
///
public interface IStudentRepository
{
string GetName(long id);
}

然后让StudentRepository去实现这个接口:

/// 
/// 学生仓储
///
public class StudentRepository : IStudentRepository
{
public string GetName(long id){
return "学生张三";//造个假数据返回
}
}

然后在StudentService里只依赖于IStudentRepository,以后的增删改查都通过IStudentRepository这个抽象来做:

/// 
/// 学生逻辑处理
///
public class StudentService
{
private readonly IStudentRepository _studentRepository;
public StudentService(){
_studentRepository = new StudentRepository();
}
public string GetStuName(long id){
var stu = _studentRepository.Get(id);
return stu.Name;
}
}<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值