为什么我应该将IHttpContextAccessor作为Singleton注入 [英] Why should I inject IHttpContextAccessor as a Singleton

查看:129
本文介绍了为什么我应该将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?

推荐答案

辛格尔顿真的是推荐的方式吗?

Is Singleton really the recomended way?

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

According to comments associated with an issue raised on GitHub

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

在该示例中,您将其注册为单例.它不应该是一个有作用域的实例吗?

In that sample, you are registering it as a singleton. Shouldn't it be a scoped instance?

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

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

稍后收到哪个回复

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

实际上,如果您将其注册为.NET Core上的Transient,则它将无法正常工作,因为.NET Core的实现使用的是AsyncLocal,该实例依赖实例变量来跟踪线程本地存储插槽.因此,必须在.NET Core上将其注册为单例.

Actually if you register it as a Transient on .NET Core then it doesn't work properly since the implementation for .NET Core is using a AsyncLocal which relies upon the instance variable to track the thread local storage slot. So it has to be registered as a singleton on .NET Core.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆