Take the following scenario. I have multiple ASPX pages. Login, Logout, Main, Messages, etc… They all inherit from System.Web.UI.Page of course. For all the pages, I want to override the Render method from the Page class. I could easily copy and paste the same code into each page like so:
protected override void Render(HtmlTextWriter writer)
{
//Code Logic Here
}
But if I had many pages, lets say 20, maintaining the code in each page could get very time consuming and error prone.
That made me think a bit and I thought okay lets try this…override the function in each page but call a static function. That way changing the static function would result in a change for every page. Which works fine… But its not really nice and clean, having to override like that on every single page. Anybody have any ideas or thoughts on this one? Perhaps something simple I am overlooking? Thanks
EDIT: Some pages use the System.Web.UI.Page class and some pages inherit from another class called ModifiedPage which inherits and overridies other functions of the System.Web.UI.Page class. So its not as simple as inheriting all the pages from one class.
EDIT2: All pages need this behavior, some already derive from another class, and I am unable to change the implementation or inheritance hierarchy of that other class.
Instead of inheriting from
System.Web.UI.Page, have them all inherit fromMyProject.MyBasePagewhich inherits from Page:and…
Edit
Clarification added to the question now points out the real puzzle – the pages which all need this common Render logic have different inheritance paths. That is more tricky in c#, and you won’t be able to avoid at least a little bit of redundant plumbing code. There’s plenty of different ways to handle this – here’s one approach I have taken in the past:
1) Create an interface for this common functionality. For example,
IOverrideRender:2) Each page which needs this functionality gets the interface and wires it like so:
3) In an HttpModule, check to see if the handler is
IOverrideRenderand if so, pass in your custom render method: