我有一些数据层类,几乎在整个站点上都会被非常频繁地使用。
我以前在 Windows 应用程序上工作,我曾经在模块 (vb.net) 中创建它的对象,但现在我在 C# 和 ASP.NET 上工作。
现在我需要做同样的事情,这样我就不需要在每个页面上多次创建相同的对象。
我想使用类似使用全局变量的东西。
我该怎么做?
是不是用global.asax
我可以在 global.asax 中创建我的对象吗
我是 asp.net 的新手,所以尽量给出语法和解释。
最佳答案
您实际上不需要使用 global.asax。您可以创建一个类,将您的对象公开为 static
。这可能是最简单的方法
public static class GlobalVariables {
public static int GlobalCounter { get; set; }
}
您还可以使用 Application State甚至 ASP.NET Cache因为这些在所有 session 中共享。
但是,如果我处于这种情况,我会使用像 Spring.NET 这样的框架。管理我所有的 Sington 实例。
这是一个快速示例,说明如何使用 Spring.NET 获取类实例
//The context object holds references to all of your objects
//You can wrap this up in a helper method
IApplicationContext ctx = ContextRegistry.GetContext();
//Get a global object from the context. The context knows about "MyGlobal"
//through a configuration file
var global = (MyClass)ctx.GetObject("MyGloblal");
//in a different page you can access the instance the same way
//as long as you have specified Singleton in your configuration
但实际上,这里更大的问题是为什么需要使用全局变量?我猜你并不真的需要它们,可能有一个更好的大局解决方案适合你。
关于c# - 如何创建全局变量,ASP.NET,全局asax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1797568/