This is part 1 of a series of posts on the Builder Design Pattern inspired by the DbConnectionStringBuilder class in ADO.NET 2.0:
- Part 1 introduces the DBConnectionStringBuilder and SqlConnectionStringBuilder Classes.
- Part 2 describes the Builder Design Pattern.
- Part 3 discusses a simple SqlSelectQueryBuilder Class to provide another example of the Builder Design Pattern.
DbConnectionStringBuilder
During further reading of Pro ADO.NET 2.0, I came across a new class in ADO.NET 2.0, called DbConnectionStringBuilder, which serves as a base class for strongly typed connection string builders. The DbConnectionStringBuilder class provides the base class from which the strongly typed connection string builders (SqlConnectionStringBuilder, OleDbConnectionStringBuilder, and so on) derive. The connection string builders let developers programmatically create syntactically correct connection strings, and parse and rebuild existing connection strings.
The DBConnectionStringBuilder sits in the System.Data.Common namespace to provide a datastore agnostic interface. You would work with it like this:
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder();
builder.DataSource = "(local)";
builder.InitialCatalog = "Product";
builder.IntegratedSecurity = true;
SqlConnection connection =
new SqlConnection(builder.ToString());
// ...
As you can tell from the above code, you are building a connection string in a very object-oriented way step-by-step, and you don't need any intimate knowledge about connection string formats. Once you have set all of the properties particular to your environment in any order, it is the call to the ToString() method that outputs an appropriate connection string for you.
You decide the usefulness of this class in your particular applications or framework. I am more interested in the fact that this is a great example of the Builder Design Pattern, which I will talk about in Part 2.
Recent Posts on SQL Server and ADO.NET 2.0