Adventures in creating controls - Know your application lifecycle

ASP.Net Add comments

kick it on DotNetKicks.com

I have been developing Composite Controls lately for ASP.Net. I am trying to focus on clean separation of code and adhering to DRY principles whenever possible. This has lead me to using controls in an attempt to make my application modules more “pluggable” with the application core.

So far this has been working quite well but I am being forced to investigate the lifecycle of the different components of my application when I encounter results that I wasn’t expecting.

Simple Example

We’ll look at a simple example in a moment. I approached control development the same way that I approach, what I would call normal, OOP concepts in C#. I initialize the objects, load necessary data, yada yada yada. What I found is that controls throw a whole new twist on the lifecycle of my application.

MyControl.cs

namespace MyCustomControls {
	public class MyControl : CompositeControl {
		//private members
		private string myProperty;

		// constructor
		public MyControl() {
			this.Initialize();
		}

		//some property
		public string MyProperty {
			get { return myProperty; }
			set { myProperty = value; }
		}

		// Removes <span></span> from around control
		protected override void Render(HtmlTextWriter writer) {
			RenderContents(writer);
		}

		// creates the controls
		protected override void CreateChildControls() {
			//create my controls here
		}

		//initialize the control
		private void Initialize() {
			HttpContext.Current.Response.Write(myProperty);
		}
	}
}

Default.aspx

...
<%@ Register TagPrefix="custom" Namespace="MyCustomControls" Assembly="MyCustomControls" %>
...
<custom:MyControl ID="MyControl1" runat="server" MyProperty="Some property"/>
...

The above example illustrates how I first approached developing controls. Some of you may cringe at this code, I don’t know. I don’t claim to be a .Net or Patterns guru so feel free to call me out on bad code.

So what’s the problem?

So what’s the problem? Well the Initialize method will write a null string to the screen. Why? Because properties are not set until after the constructor is called so I am trying to write the property before it has be instantiated .

How I made it work

What I did to achieve the results I needed I removed the call to the Initialize method from the constructor and placed it at the top of the CreateChildControls method.

// creates the controls
protected override void CreateChildControls() {
	this.Initialize();
	//create my controls here
}

Conclusion

Again I am not sure if this is the best approach, since I am fairly new to creating controls, but this is what works for me. I would welcome your opinions and views on this.

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Login