3

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.

The Cline
  • 171
  • 3
  • 9
  • Shouldn't Application[""] in that scope be the same as HttpContext.Current.Application? Where are you assigning it? ie: HttpContext.Current.Application["Store"] = Store. – LouD Apr 12 '13 at 20:09

2 Answers2

3

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

spender
  • 117,338
  • 33
  • 229
  • 351
  • I did move the UserDataStore class to a 3rd project because it was in the Web project. But we still want to use the Application/Session Start/End events in Global.asax.cs. Slo the storage of the UserDataStore object should remain there. – The Cline Apr 12 '13 at 21:17
  • 1
    @Chris Cline : Why? You seem to have placed a strange constraint on yourself. You could, for instance, have a static property on the UserDataStore itself, and simply access that from global.asax. Just because you use it in global.asax doesn't mean that you have to define the holding field there too. – spender Apr 13 '13 at 00:08
  • 1
    What can I say? I like strange constraints. But seriously, I took your advice and refactored our code accordingly. It appears to be working smoothly so far. Thanks! – The Cline Apr 16 '13 at 14:52
1

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
LouD
  • 3,776
  • 4
  • 19
  • 17