PDA

View Full Version : HttpContext.Current.Handler cast fails


smhinsey
12-27-2005, 08:14 PM
I have a class library that relies on a pluggable strategy architecture to swap in different components.

Since this particular strategy executes in the web UI layer, I need to be able to access the current instance of Spring.Web.UI.Page in order to get at the application context.

However, casting HttpContext.Current.Handler to Spring.Web.UI.Page fails. Interestingly enough, performing such a cast in a QuickWatch expression evaluator succeeds.

Any ideas? Is there a better way of getting at the application context?

smhinsey
12-27-2005, 08:21 PM
That was a real RTFM question...

In case anyone else has the same slip-up, you want to use WebApplicationContext.Current.

Aleks Seovic
12-27-2005, 09:44 PM
Yup, you should *always* use WebApplicationContext.Current to retreive application context within a class that does not implement IApplicationContextAware, as that's the only way to ensure thread safety.

That said, it might be worth to explain why your cast was failing, because it's definitely not obvious nor expected behavior.

Basically, when you are working with a page that is defined within Spring context, HttpContext.Current.Handler will never return the page itself. Instead, it will return either an instance of the internal PageHandler class, or more commonly and instance of the SessionAwarePageHandler.

These classes are a thin wrappers that retrieve page from the context and delegate request processing to it and they are primarily needed in order to enable session scoped objects. However, they do provide an additional feature that comes in very handy in certain situations -- a thread-safe shared state for all the pages of the same type.

This shared page state is used for example within the framework to cache localization resources and data binding definitions for the page, and you can easily leverage it within your applications by using Page.Items property.

HTH,

Aleks