ASP.NET Core 自带IOC容器如何依赖注入

ASP.NET Core 本身已经集成了一个轻量级的IOC容器,开发者只需要定义好接口,在Startup.cs的ConfigureServices方法里使用对应的生命周期的绑定方法即可

案例中  IC  表示接口 , C 表示 IC 的实现

//注册数据库基础操作
services.AddScoped(typeof(IC), typeof(C));
//注册缓存操作
services.AddTransient(typeof(IC), typeof(C));
services.AddScoped(typeof(IC), typeof(C));
services.AddSingleton(typeof(IC), typeof(C));

或者

services.AddTransient<IC, C>();
services.AddScoped<IC, C>();  
services.AddSingleton<IC, C>(); 
  • AddTransient(瞬时) : 服务在每次请求时被创建
  • AddScoped(作用域单例) : 服务在每次请求时被创建,生命周期横贯整次请求
  • AddSingleton(单例) : 服务在第一次请求时被创建(或者当我们在ConfigureServices中指定创建某一实例并运行方法),其后的每次请求将沿用已创建服务
原文地址:https://www.cnblogs.com/sunhouzi/p/12107515.html