.net 6手动获取注入服务实例
作者:互联网
第一种实现方式(不推荐)
var services = new ServiceCollection(); var provider = services.BuildServiceProvider(); var _demoService = provider.GetService<IDemoService>();View Code
第二种实现方式(推荐)
.net6实现方式
public static class ServiceLocator { public static IServiceProvider Instance { get; set; } } --program文件中 var app=buidler.Build(); ServiceLocator.Instance =app.Service(); --demo方法 public void DemoMethod() { var demoService = ServiceLocator.Instance.GetService<IDemoService>(); }View Code
.net core 3.1实现方式
public void Configure(IApplicationBuilder app) { ServiceLocator.Instance = app.ApplicationServices; } public static class ServiceLocator { public static IServiceProvider Instance { get; set; } } public void DemoMethod() { var demoService = ServiceLocator.Instance.GetService<IDemoService>(); }View Code
注意:使用ServiceLocator.Instance.GetService()只能获取AddTransient和AddSingleton注入的对象,而不能获取AddScoped(请求生命周期内唯一)注入的对象,因为获取的对象和构造函数获取的不是同一个(即获取的对象没有共享),使用场景比如IUnitOfWork。
那怎么手动获取请求生命周期内的注入对象呢?方法如下:
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace Domain { public class DemoService : IDemoService { private IUnitOfWork _unitOfWork; public DemoService (IHttpContextAccessor httpContextAccessor) { _unitOfWork = httpContextAccessor.HttpContext.RequestServices.GetService<IUnitOfWork>(); } } }View Code
标签:ServiceLocator,获取,手动,GetService,Instance,实例,var,net,public 来源: https://www.cnblogs.com/donchen/p/16484705.html