The Cline
The Cline

Reputation: 161

Having problems accessing Public Static variable in Global.asax.cs using HttpContext.Current (C#)

In a Web Project, I've defined a Public Static variable (Store) in global.asax.cs that needs to be accessible throughout the application.

public class Global : HttpApplication
{
    public static UserDataStore Store;

    void Application_Start(object sender, EventArgs e)
    {
        Store = new UserDataStore();
        Store.CurrentUsers = new Hashtable();
    }

    void Session_Start(object sender, EventArgs e)
    {
        if (!Store.UserExists(HttpContext.Current.Session.SessionID))
            Store.AddUser(HttpContext.Current.Session.SessionID, "StubUser");
    }
}

I need to access it in another project that can't reference the Web Project (and it's Global object) because it would cause a circular reference.

My work-around for that was to try and retrieve Store using the HttpApplication object:

UserDataStore udStore = (UserDataStore) HttpContext.Current.Application["Store"];

This compiles, but returns a null object.

I've gone Google-blind trying to find other examples like this, but most of what I've found espouses one of 2 approaches:

  1. Use Application[""] variables, which is sub-optimal and intended for Classic ASP compatibility according to this article: http://support.microsoft.com/kb/312607
  2. Access it via the Web project's Global class, which is not an option in our current setup.

This seems like it should be possible, so hopefully I'm missing something stupid.

Any help you can provide would be greatly appreciated. Thanks.

Upvotes: 3

Views: 3003

Answers (2)

LouD
LouD

Reputation: 3844

Application[""] should be the same as HttpContext.Current.Application. Did you remember to add that value? You could call either of these from your Application_Start.

Application["Store"] = Store 

or

HttpContext.Current.Application["Store"] = Store

Upvotes: 1

spender
spender

Reputation: 120380

Make a third (library) project with the shared data and reference it from both of your other projects.

Upvotes: 3

Related Questions