ASP.NET Core DI 一般使用构造函数注入获取对象,比如在ConfigureServices
配置注入后,通过下面方式获取:
private IValueService _valueService;
public ValueController(IValueService valueService)
{
_valueService = valueService;
}
那如果手动获取注入对象呢?
第一种获取方式(有时会获取不到,不推荐使用):
var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
var _valueService = provider.GetService<IValueService>();
第二种获取方式(推荐使用):
public void Configure(IApplicationBuilder app)
{
ServiceLocator.Instance = app.ApplicationServices;
}
public static class ServiceLocator
{
public static IServiceProvider Instance { get; set; }
}
public void SomeRandomMethod()
{
var valueService = ServiceLocator.Instance.GetService<IValueService>();
// Do something with service
}
补充:需要注意的是,使用
ServiceLocator.Instance.GetService<T>();
,只能获取AddTransient
和AddSingleton
注入的对象,而不能获取AddScoped
(请求生命周期内唯一)注入的对象,不是不能获取,而是获取的和构造函数获取的不是相同对象,也就是说获取的对象没有共享,使用场景比如IUnitOfWork
。
那怎么手动获取请求生命周期内的注入对象呢?方法如下:
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Sample.Domain
{
public class SampleDomainService : IDomainService
{
private IUnitOfWork _unitOfWork;
public SampleDomainService(IHttpContextAccessor httpContextAccessor)
{
_unitOfWork = httpContextAccessor.HttpContext.RequestServices.GetService<IUnitOfWork>();
}
}
}
IHttpContextAccessor
接口在Microsoft.AspNetCore.Http.Abstractions
Nuget 程序包下。
参考资料:
- Accessing IServiceProvider in static context
- No way to get scope for current http request (Autofac 4)?
原文地址:https://www.cnblogs.com/lonelyxmas/p/10952969.html
时间: 2024-10-03 18:21:01