1.依赖注入-服务注册、移除、替换
一、组件包
Microsoft.Extensions.DependencyInjection.Abstractions
Microsoft.Extensions.DependencyInjection
二、核心类型
IServiceCollection
ServiceDescriptor
IServiceProvider
IServiceScope
三、生命周期:ServiceLifetime
单例 Singleton
作用域 Scoped:每次请求作用域是不同的,同一请求内是同一个对象
瞬时(暂时) Transient
四、服务注册、移除、替换
1、注册服务不同生命周期的服务
services.AddSingleton<IMySingletonService, MySingletonService>(); services.AddScoped<IMyScopedService, MyScopedService>(); services.AddTransient<IMyTransientService, MyTransientService>();
2、花式注册
services.AddSingleton<IOrderService>(new OrderService()); //直接注入实例 services.AddSingleton<IOrderService, OrderServiceEx>(); services.AddSingleton<IOrderService>(serviceProvider => { return new OrderServiceEx(); });
3、尝试注册
services.TryAddSingleton<IOrderService, OrderServiceEx>();//如果服务中已注册IOrderService接口就不注册,以接口作区分。 services.TryAddEnumerable(ServiceDescriptor.Singleton<IOrderService, OrderServiceEx>());//如果服务中已注册相同的实现类就不注册,不同的实现类就注册,已实现类作区分。
4、注册泛型模板
services.AddSingleton(typeof(IGenericService<>), typeof(GenericService<>));
5、移除和替换注册
services.Replace(ServiceDescriptor.Singleton<IOrderService, OrderServiceEx>());
services.RemoveAll<IOrderService>();
五、依赖对象的获取
1、构造函数方式
public WeatherForecastController(ILogger<WeatherForecastController> logger, IOrderService orderService, IGenericService<IOrderService> genericService) { _orderService = orderService; _logger = logger; }
2、控制器方式
public int GetService([FromServices]IMySingletonService singleton1) {return 1; }
//FromServices]IEnumerable<IOrderService> services //从服务中获取所有注入过IOrderService的对象
public int GetServiceList([FromServices]IEnumerable<IOrderService> services) { foreach (var item in services) { Console.WriteLine($"获取到服务实例:{item.ToString()}:{item.GetHashCode()}"); } return 1; }
3、服务方式
var obj= HttpContext.RequestServices.GetService(typeof(IOrderService));