2

Normally, when we need a reference to the current Application state, we'd use:

HttpContext.Current.Appliction

But there are times that there's no current HttpContext (HttpContext.Current returns null). How can I obtain a reference to the current application instance in that case?

An example can be in Session_End event. Although I can use Application property inside the Session_End event handler, but what if the handler calls a library method and the HttpApplicationState object is required in the library code? I don't like to pass an "application" parameter around...

I also don't like keeping it in a static field (like Singleton pattern) and I'm looking for a way to directly get it from context.

Is there any way to access the instance directly (similar to HttpContext.Current.Application approach) or do I have to choose one of the above not-so-clean methods?

Iravanchi
  • 5,139
  • 9
  • 40
  • 56
  • I know when you have generic handler pages (IHttpHandler) you can implement IRequiresSessionState to make the state available. – ToddBFisher Apr 04 '13 at 00:07
  • There is nothing unclean about using a static/singleton pattern in this instance, in my opinion. In fact, I would encourage it. – Moby's Stunt Double Apr 04 '13 at 00:24
  • @Moby I don't have any hard arguments against it, but I'd like something as clean and independent as `HttpContext.Current`. Consider the case where I'm writing a library code that wants access to Application, and another person wants to use it. If I define the Singleton, he still needs to fill it for me. If he defines it, I wouldn't have access to it. In this case, the best way can be writing a module and making him register it. Compare it to HttpContext.Current... It "could" be much easier and cleaner if the Framework gave us some options. – Iravanchi Apr 04 '13 at 00:30

1 Answers1

2

I'd use HttpRuntime.Cache instead of the application-state object. HttpRuntime.Cache can be used from anywhere.

Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149