此“请求范围服务提供者”的实现和使用可能带来什么影响或副作用?
public interface IScopedServiceProvider : IServiceProvider
{
}
public class ScopedServiceProvider : IScopedServiceProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ScopedServiceProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public object GetService(Type serviceType)
{
return _httpContextAccessor.HttpContext.RequestServices.GetService(serviceType);
}
}
目标基本上是从给定的单例服务访问作用域服务:
像这样在容器中注册:
services.AddHttpContextAccessor();
services.AddScoped<IScopedServiceProvider, ScopedServiceProvider>();
services.AddScoped<IMyScopedService, MyScopedService>();
services.AddSingleton<IMySingletonService, MySingletonService>();
像这样使用:
public class MySingletonService : IMySingletonService
{
private readonly IScopedServiceProvider _scopedServiceProvider;
public MySingletonService(IScopedServiceProvider scopedServiceProvider)
{
_scopedServiceProvider = scopedServiceProvider;
}
public void DoWork()
{
var scopedService = _scopedServiceProvider.GetService<IMyScopedService>();
scopedService.DoAnotherWork();
}
}