标签:隐式 技术 第一步 options vat dcom tar 相同 ext
课程链接:http://video.jessetalk.cn/course/explore
良心课程,大家一起来学习哈!
1、依赖注入概念详解
2、ASP.NET Core 源码解析
当一个类A完成某个任务需要另一个类B来帮助时,A就对B产生了依赖
例如CustomerController需要对customer进行新增或查找时用到EF,则对EF的Context产生了依赖
var context = new CustomerContext(new DbContextOptions<CustomerContext>{});
显示依赖:把一个类用到的所有外部组件放到一个类最上面,在构造函数里面初始化
private CustomerContext _context;
public CustomerController()
{
_context = new CustomerContext(new DbContextOptions<CustomerContext>{});
}
隐式依赖:需要用到的地方再初始化,不推荐
var context = new CustomerContext(new DbContextOptions<CustomerContext>{});
依赖高层业务,不依赖低层业务的具体实现,而依赖于具体的抽象
CustomerController是高层业务的一个组件,依赖于CustomerContext是一个低层数据库的实现,如果现在需要把EF换成一个内存的实现或者mysql,需要修改CustomerController类,风险很大,所以应该依赖于低层业务的抽象
把低层业务方法抽象,比如查找,新增,抽象出一个接口,当不需要使用EF的时候,使用内存的实现替换
private ICustomerRepository _customerRepository;
public CustomerController()
{
_customerRepository = new EfCustomerRepository(
new CustomerContext(new DbContextOptions<CustomerContext>{}));
}
实现依赖注入的方式不由自己决定,而是交给一个IOC容器,需要什么由容器传入,比如生产环境需要使用EF,则由容器传入一个EfCustomerRepository,而测试环境需要使用内存级别的,则传入一个MemoryCustomerRepository
private ICustomerRepository _customerRepository;
public CustomerController(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
var repository = new Data.MemoryCustomerRepository();
var controller = new CustomerController(repository);// 通过外部控制Controller里面的依赖
var customer = new Model.Customer()
{
FirstName = "Mingson",
LastName = "Zheng",
Phone = "123456789",
};
var result = controller.Add(customer);
Assert.IsType<OkResult>(result);// 正确结果
var resultBad = controller.Add(customer);
Assert.IsType<BadRequestObjectResult>(resultBad);// 错误结果
http://www.jessetalk.cn/2017/11/06/di-in-aspnetcore/
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。
如有任何疑问,请与我联系 (504025730@qq.com) 。
ASP.NET Core快速入门(Jessetalk)(第三章:依赖注入)
标签:隐式 技术 第一步 options vat dcom tar 相同 ext
原文地址:https://www.cnblogs.com/MingsonZheng/p/10328549.html