ASP.NET 中的单例安全性如何?

发布于 2025-01-12 22:08:52 字数 99 浏览 3 评论 0原文

ASP.NET 中的单例是否在用户/会话之间共享?如果是的话,是否有任何安全考虑?想想序列化/反序列化漏洞、线程安全等。

这是使用数据库中对所有用户都相同的设置的方法吗?

Are singletons in ASP.NET shared between users/sessions? And if they are, are there any safety considerations? Think serializing/deserializing vulnerabilities, thread safety etc.

Is it the way to go using settings from the database that are the same for all users?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寻找一个思念的角度 2025-01-19 22:08:52

一般来说,无论是否是 ASP.NET,在 C# 代码中手工制作名为“Singleton”的反模式都是一个非常糟糕的主意。

如果依赖注入框架支持的单例生命周期能够满足您的需要,那么它是一个好主意。

不过,我建议您仅将其用于只读数据,例如设置。您的桌面上没有以前的应用程序。您的应用程序可能会动态回收,或者可能跨服务器场上的多个节点延伸。因此,如果您的程序只有一个实例正在运行,那么突然间您的“单例”实际上只是一个单例。构建您的应用程序,使其成为一个人为问题(即框架将支持它,但如果您确实这样做,您自己的代码就会失败)并不是解决此问题的明智方法。

总结一下:依赖注入容器中的单例生命周期?可能没问题。取决于您的用例。您的代码中是否有实际的“单例”模式?坏的。非常糟糕。告诉我,您实际上并没有进行任何单元测试,也没有计划将该应用程序带给数千名业余爱好者用户,他们不关心您的应用程序是否在每次部署时关闭。

Hand crafting the anti-pattern called "Singleton" in C# code is a really bad idea in general, ASP.NET or not.

The singleton lifetime that is supported in the dependency injection framework is a good idea if it does what you need.

I would advise you to only use it for read-only data, like settings, though. You don't have an application on the desktop as of old. Your application might be recycled on the fly, or maybe stretched across multiple nodes on a server farm. So suddenly your "singleton" is actually only a singleton if you have a single instance of your program running. Building your application so this becomes an artificial problem (i.e. the framework would support it, but your own code is build to fail if you actually do so) is not a smart way to go about this.

So to summarize: Singleton lifetime in your dependency injection container? Might be okay. Depends on your use case. An actual "Singleton" pattern in your code? Bad. Very Bad. Tells me you don't actually do any unit testing and nothing is planned to bring this application over a few thousand hobbyist users who don't care if your app is down every time you deploy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文