如何创建全局变量,ASP.NET,全局asax

Sha*_*pta 9 .net c# asp.net global-asax

我有一些数据层类,几乎在整个网站上都经常使用.

我之前正在开发一个Windows应用程序,我曾经在模块(vb.net)中创建它的对象,但现在我正在使用C#和ASP.NET.

现在我需要做同样的事情,这样我就不需要在每个页面上多次创建相同的对象.
我想使用像使用全局变量之类的东西.

我怎样才能做到这一点?
它是通过使用global.asax完成的,
我可以在global.asax中创建我的对象

我是asp.net的新手,所以尽量给出语法和解释.

Bob*_*Bob 9

您实际上不需要使用global.asax.您可以创建一个将对象公开为statics的类.这可能是最简单的方法

public static class GlobalVariables {
    public static int GlobalCounter { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用Application State甚至ASP.NET Cache,因为它们在所有会话中共享.

但是,如果我遇到这种情况,我会使用像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
Run Code Online (Sandbox Code Playgroud)

但实际上,这里更大的问题是为什么你需要使用全局变量?我猜你真的不需要它们,你可能会有一个更好的大图片解决方案.