net6 类中获取服务

第一种实现方式(不推荐)

var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
var _demoService = provider.GetService<IDemoService>();

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>();
}


复制代码
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>();
}


复制代码
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>();
}
}
}


复制代码
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>();
  }
 }
}
复制代码

 原文地址:https://www.cnblogs.com/donchen/p/16484705.html

posted @ 2024-04-16 11:54  今晚再打老虎  阅读(34)  评论(0编辑  收藏  举报