(给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框架进行了初步封装,实现了相同的依赖注入效果。
项目架构如下图:
GitHub源码地址:https://github.com/WangRui321/Ray.EssayNotes.AutoFac
适用对象
该项目主要实战为主,理论部分我会结合例子和代码,深入浅出地阐述,如果你是:
从来没听过IoC、DI这些劳什子
了解一些依赖注入的理论知识但是缺乏实战
在.Net Framework下已熟练运用依赖注入,但在.NET Core还比较陌生
只要你花上半个小时认真读完每一句话,我有信心这篇文章一定会对你有所帮助。
如果你是:
发量比我还少的秒天秒地的大牛
那么也欢迎阅读,虽然可能对你帮助并不大,但是欢迎提供宝贵的意见,有写的不好的地方可以互相交流~
理论基础
依赖
依赖,简单说就是,当一个类需要另一个类协作来完成工作的时候就产生了依赖。这也是耦合的一种形式。
举个例子,比如标准的三层架构模式
数据访问层(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;
}
}<