MatthewMartin
MatthewMartin

Reputation: 33173

How to simulate multiple inheritance for ASP.NET base pages?

My project has been using a base page to hold common page functionality. Its worked until the base page grew to be huge, so I tried to factor the base page into several classes. Then I realized that I can't write

public MyPage : SecurePage, PageWithGridViewSorting, PageWithSessionWarning

given something like:

public class SecurePage : RadAjaxPage
{
    // Add session id to ViewStateUserKey
}

public class PageWithGridViewSorting : RadAjaxPage
{
    // add sorting to all grids on page
}

public class PageWithSessionWarning : RadAjaxPage
{
    // inject javascript to warn user of impending session end
}

Which way am I supposed to take this? And I think the fact that this is the ASP.NET page is relevant because it is a class that gets constructed by the framework, not me. My first thought was to make a override for the constructor and pass in the features and that wont work with System.Web.UI.Page.

Upvotes: 0

Views: 1547

Answers (3)

Welbog
Welbog

Reputation: 60438

Do the functions provided by SecurePage, PageWithGridViewSorting and PageWithSessionWarning actually need to be overloaded or overridden by their derived classes?

If all you're doing is using inheritance to group functions, you should consider using a different method of organizing functions into classes. Like, for example, the Strategy pattern. A page with sorting is a page, with sorting. It's a page that has sorting. Using inheritance isn't the right way to approach this problem.

If they do need to differ in the derived classes, you might want to approach the problem with interfaces instead of inheritance. Since you'll be redefining the functions anyway this shouldn't increase complexity or make you repeat yourself.

EDIT: Given the specifics of your problem, it really sounds to me like you should investigate aspect-oriented programming and how you can fit it into your language.

Upvotes: 4

LBushkin
LBushkin

Reputation: 131746

I think ASP.NET is an environment where you should prefer composition to inheritance. You should consider restructuring your code to "inject" the necessary functionality by composing your page from helper classes that hook into the Page events and provide the functionality. into a shared structure that other pages can use.

This can be a tricky thing to do well in ASP.NET because the page lifecycle is complex and can often "get in your way" when trying to write generic code.

You could also try to move functionality into custom or user controls, if the functionality is UI-centric.

Also, master pages are an effective way to factoring common functionality out of a page and

Upvotes: 2

Mathias F
Mathias F

Reputation: 15911

I would try to move over some of the content from BasePage to UserControls. Lets say PageWithSessionWarning. This could be a control that you put on the masterpage.

Upvotes: 3

Related Questions