.net 6中 手动获取注入服务
方法一、
var services = new ServiceCollection(); var provider = services.BuildServiceProvider(); var _demoService = provider.GetService<IDemoService>();
第二种实现方式(推荐)
.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>();
}.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>();
}注意:使用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>();
  }
 }
}