Writing A Generic Data Access Component - Flexible Approach

In response to Mahesh's article - Writing a Generic Data Access Component using ADO.NET Interfaces, here is one more flexible approach to achieve the same. I prefer this approach to generic data access.
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. public class DB {  
  5.     public static IDbConnection GetConnection() {  
  6.         Type cnType = Type.GetType(ConfigurationSettings.AppSettings("connectionType"));  
  7.         DbConnection cn = (IDbConnection) Activator.CreateInstance(cnType);  
  8.         cn.ConnectionString = ConfigurationSettings.AppSettings("connectionString");  
  9.         return cn;  
  10.     }  
  11. }  
Any application which uses above class must provide following entries in its .config file.
  1. <appSettings>  
  2.    <add key="connectionType" value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />  
  3.    <add key="connectionString" value="server=your_host;database=your_db;uid=your_uid;pwd=your_pwd" />  
  4. </appSettings>  
This approach is flexible because no recompilation is needed if a new provider is to be utilized.


Similar Articles