gpt4 book ai didi

asp.net-core - HttpContext.Items 与范围服务

转载 作者:行者123 更新时间:2023-12-02 20:56:44 25 4
gpt4 key购买 nike

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

例如:

选项 1(范围服务):

//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
}
}

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

最佳答案

根据docs :

Avoid storing data and configuration directly in DI. For example, a user’s shopping cart shouldn’t typically be added to the services container. Configuration should use the Options Model. Similarly, avoid “data holder” objects that only exist to allow access to some other object. It’s better to request the actual item needed via DI, if possible.

由于选项1是“数据持有者”的示例,因此我们应该尽可能避免它。

此外,选项 1 可能会导致 Captive Dependency如果你不注意的话。

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

关于asp.net-core - HttpContext.Items 与范围服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37180524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com