如何在 .net 6 webapi 控制器中声明全局变量并访问它们?
我正在使用 VS2022 创建一个 webapi(.net6) 项目,并尝试声明一些将在 webapi 控制器之间使用的全局变量。我这样做是怎么做的:
在项目的顶层文件夹中声明了 Dictionary 类型的静态变量:
namespace CenterWebApiHub
{
public static class ParkCenterConfigs
{
public static ConcurrentDictionary<string, string> MapToConnections = new
ConcurrentDictionary<string, string>();
}
}
如何从 Webapi 控制器访问此静态 Dictionary?请帮忙
I'm using VS2022 to create a webapi(.net6) project and trying to declaare somme gloabal variables which will be used among webapi controllers. What I did this way:
Declared static variable of type Dictionary at the top level folder of the project:
namespace CenterWebApiHub
{
public static class ParkCenterConfigs
{
public static ConcurrentDictionary<string, string> MapToConnections = new
ConcurrentDictionary<string, string>();
}
}
How to access this static Dictionary from Webapi controllers? Please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果它应该是只读的,比如设置,你应该考虑依赖注入。该文档可以在此处。
如果你想写入这个变量,你需要另一个概念。无法保证当您的应用程序池回收时该变量不会被擦除,并且它根本不可扩展。如果您必须对应用程序进行负载平衡,那么一台服务器内存中的变量将无法解决问题。
你没有说你需要它做什么,但是内存中的全局变量是处理它的最糟糕的方法。也许你应该首先寻找你想做的事情的概念。我确信其他人以前也处理过这个问题,看看他们是如何做的以及为什么。
If it is supposed to be read-only, like settings, you should look into dependency injection. The documentation can be found here.
If you want to write to this variable, you need another concept. There is no guarantee that this variable will not be wiped when your application pool recycles and it's is not scalable at all. If you ever have to load balance your application, a variable in memory of one server won't cut it.
You did not say what you need it for, but a global variable in memory is the worst way to handle it. Maybe you should start by looking for concepts of the thing you want to do. I'm sure others have handled it before, look how they did it and why.