I've been working away (http://tinyurl.com/m4hzjb) on this Fluent API for instantiating ASP.NET controls and feel I now have something that appears to work well. I'm looking for some feedback and opinions... good, bad or indifferent. Would you find this useful? Any technical issues you foresee? Room for improvement?
Here's a very basic usage sample for creating a standard TextBox control. Only two properties/methods are implemented, but API could easily be expanded to support full property feature set of control(s).
USAGE
Factory.TextBox()
.ID("TextBox1")
.Text("testing")
.RenderTo(this.form1);
// The above TextBox Builder is functionally same as:
TextBox textbox = new TextBox();
textbox.ID = "TextBox1";
textbox.Text = "testing";
this.form1.Controls.Add(textbox);
// Or:
this.form1.Controls.Add(new TextBox {
ID = "TextBox1",
Text = "testing"
});
Here's the full ControlBuilder class.
BUILDER
public partial class Factory
{
public static TextBoxBuilder TextBox()
{
return new TextBoxBuilder(new TextBox());
}
}
public abstract class ControlBuilder<TControl, TBuilder>
where TControl : Control
where TBuilder : ControlBuilder<TControl, TBuilder>
{
public ControlBuilder(TControl control)
{
this.control = control;
}
private TControl control;
public virtual TControl Control
{
get
{
return this.control;
}
}
public virtual void RenderTo(Control control)
{
control.Controls.Add(this.Control);
}
public TBuilder ID(string id)
{
this.Control.ID = id;
return this as TBuilder;
}
}
public abstract class TextBoxBuilder<TTextBox, TBuilder> : ControlBuilder<TTextBox, TBuilder>
where TTextBox : TextBox
where TBuilder : TextBoxBuilder<TTextBox, TBuilder>
{
public TextBoxBuilder(TTextBox control) : base(control) { }
public TBuilder Text(string text)
{
this.Control.Text = text;
return this as TBuilder;
}
}
public class TextBoxBuilder : TextBoxBuilder<TextBox, TextBoxBuilder>
{
public TextBoxBuilder(TextBox control) : base (control) { }
}