net core 3.1 依赖注入

Netcore内置IOC容器,services.AddSingleton<>,
就是往内置IOC容器里配置一个单例,将接口跟实现映射在一起,
以后每次使用构造函数注入这个IProductRepository接口,
都会获得这个单例对象! 不需要new ProductRepository()

DI --注入, IOC就是对象的容器, 配合起来就是依赖注入,按软件设计原则来说,这叫控制反转的作用

 


1.public interface HomeIBLL

2.public class HomeBLL : HomeIBLL
{
private readonly HomeIRepository _homeIRepository;
public HomeBLL(HomeIRepository homeIRepository)
{
_homeIRepository = homeIRepository;
}

3.public interface HomeIRepository

4.public class HomeRepository : HomeIRepository


5.services.AddSingleton<HomeIBLL, HomeBLL>();
services.AddSingleton<HomeIRepository, HomeRepository>();

6.private readonly HomeIBLL _homeIBLL;

public HomeController(ILogger<HomeController> logger, HomeIBLL homeIBLL)
{
_logger = logger;
_homeIBLL = homeIBLL;
}

net core 3.1 依赖注入

上一篇:移动端下弹框禁止背景滑动


下一篇:http格式详解