I’ve got a complicated ASP.NET project (ASP.NET 2.0) and i’m trying to refactor the code a little.
Every page extends a base page called GenericPage which has a set of functions which are used in the page life-cycle (functions which access the session/HttpApplicationState object). There are also quite a few user controls which do a similar thing but extend a separate base class.
We are starting re-implement a lot of the code to use WebServices and they need to have access to the same functions. The WebServices will extend GenericWebService.
What’s the best way to architect this given that both cannot extend from the same class given that one extends Page and one extends WebService? I don’t want to duplicate the code in 3 separate base classes as it is getting increasingly difficult to maintain.
Is there a common place that I can put these non-static functions?
Thanks
You can create a class that uses HttpContext.Current to access the session and such. This class doesn’t need to descend from anything, and you just inject (or otherwise instantiate) it into your basepage and base web service.
Here’s an example of what the class might look like; I have a helper property for accessing the Session object easily, and a simple property storing the current user ID. You may want more error handling, or to access things other than the session, but it should be pretty straightforward how to do anything more.
Then in your Basepage:
The last bit would be either changing all of your current BasePage properties that are accessing the Session directly to instead access via the WebSession property or to change all the referring code to get it (removing the helper properties from the BasePage).