本文介绍了为什么我应该将IHttpContextAccessor作为Singleton注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我见过的 IHttpContextAccessor 注入的所有示例中,它都设置为Singleton.

In all examples that i've seen of IHttpContextAccessor injection, it is set as a Singleton.

示例:

将IHttpContextAccessor注入ApplicationDbContext ASP.NET Core 1.0 .NET Core IHttpContextAccessor问题

我觉得有点奇怪,因为 HttpContext 确实看起来像映射到请求的东西.在这种情况下, AddScoped 是否更合适?

I find it kinda weird, since HttpContext really looks like something that maps to requests. Wouldn't AddScoped be more appropriate in this case?

辛格尔顿真的是推荐的方式吗?我没看见什么吗?

Is Singleton really the recomended way? Am I not seeeing something?

推荐答案

根据与在GitHub上引发的问题相关的评论

According to comments associated with an issue raised on GitHub

https://github.com/aspnet/Hosting/issues/793#issuecomment-224828588

最好是单身,因为后备存储是异步本地的.

It's fine being a singleton because the backing store is async local.

稍后收到哪个回复

https://github.com/aspnet/Hosting/issues/793#issuecomment-224924030

这篇关于为什么我应该将IHttpContextAccessor作为Singleton注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 18:21