HttpContext.Items vs Scoped Service

ade*_*lin 8 asp.net-core

哪种方式更好的携带请求数据(两种方式之间有什么区别)?

例如:

选项1(Scoped Service):

//Scoped Service(this may be interface)
public class SampleScopedService
{
    public string Data { get; set; }
}

//Register service
services.AddScoped<SampleScopedService>();

//Set and Get Data
public class SampleUsage
{
    private readonly SampleScopedService _sampleScopedService;
    public SampleUsage(SampleScopedService sampleScopedService)
    {
        _sampleScopedService = sampleScopedService;
        // _sampleScopedService.Data = "Sample";
        // _sampleScopedService.Data 
    }
}
Run Code Online (Sandbox Code Playgroud)

选项2(HttpContext.Items)

//Scoped Service
public class SampleScopedService
{
    private readonly IHttpContextAccessor _accessor;

    public SampleScopedService(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
    public string GetData()
    {
        return (string)_accessor.HttpContext.Items["Data"];
    }
}

//Register service
services.AddScoped<SampleScopedService>();

//Set Data
HttpContext.Items[“Data”] = ”Sample”;

//Get Data
public class SampleUsage
{
    private readonly SampleScopedService _sampleScopedService;
    public SampleUsage(SampleScopedService sampleScopedService)
    {
        _sampleScopedService = sampleScopedService;
        //_sampleScopedService.GetData();
    }
}
Run Code Online (Sandbox Code Playgroud)

ade*_*lin 5

根据文件:

避免直接在DI中存储数据和配置.例如,通常不应将用户的购物车添加到服务容器中.配置应使用选项模型.同样,避免仅存在的"数据持有者"对象以允许访问某些其他对象.如果可能的话,最好通过DI请求所需的实际项目.

由于选项1是"数据持有者"的例子,我们应尽可能避免它.

此外,如果您不注意,选项1可能会导致强制依赖.

因此,使用具有单例生命周期的选项2比使用选项1更好.