使用IHttpContextAccessor从单例中获得作用域服务是否正确?

时间:2018-09-12 03:00:08

标签: asp.net-web-api asp.net-core dependency-injection singleton httpcontext

此“请求范围服务提供者”的实现和使用可能带来什么影响或副作用?

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

0 个答案:

没有答案