Hi,
I got an abstract class BasePage that inherits System.Web.UI.Page for a web application, and actual pages are supposed to inherit this BasePage instead of Page directly.
The BasePage needs to create some object in its constructor using a Configuration. A Configuration is a class related to NHibernation (doesn't really matter for my question).
However, as far as I know I cannot pass this configuration via the constructor because in ASP.NET you never call the constructor of a page directly (in each case, I wouldn't know how to pass parameters to the constructor of a page even if it is possible).
So I need some other way to get the information in the constructor. I thought I could use an abstract property that the derived class has to override in which it can return the Configuration object, so I did this:
My reasoning is that now, a deriving page can do supply the configuration from wherever it gets it from (for example, a session variable or whatever):csharp Code:
public abstract class BasePage : System.Web.UI.Page { public BasePage() // cannot use parameters here { // Get the configuration it needs to use Configuration config = this.Configuration; // And use it this.CreateObjectFromConfiguration(config); } public abstract Configuration Configuration { get; } //... }
csharp Code:
public class ActualPage : BasePage { public override Configuration Configuration { get { return (Configuration)this.Session["Configuration"]; } } }
While conceptually this seemed to fit, ReSharper gave me a warning on line 6 of the first code sample, saying "Virtual member call in constructor". I googled the warning and I came up with a few threads that explain why this can be a problem. If I understand it correctly, in my example, the constructor of BasePage would request the Configuration property in the deriving class (ActualPage.Configuration), but the deriving class has not been created yet. I guess that this.Session["Configuration"] would then return null?
I am not in the opportunity to test it with the actual page objects at the moment, so I created a little test where I replaced Configuration with a simple Button:
Indeed, when I run this, I get a null reference exception on the Debug.WriteLine method as 'btn' is null.csharp Code:
class Program { static void Main(string[] args) { var page = new ActualPage(); } } public abstract class BasePage { public BasePage() { Button btn = this.Button; Debug.WriteLine(btn.Text); } public abstract Button Button { get; } } public class ActualPage : BasePage { private Button b; public ActualPage() { b = new Button {Text = "test"}; } public override Button Button { get { return b; } } }
How can I solve this problem? How can I pass the Configuration (or the Button in my example) to the constructor of the BasePage without passing it via a parameter as usual?
Thanks!




Reply With Quote