net6 類中獲取服務

今晚再打老虎發表於2024-04-16

第一種實現方式(不推薦)

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

相關文章