Last active
August 29, 2015 14:27
-
-
Save pjsvis/65e0e5efd16eb1d4e100 to your computer and use it in GitHub Desktop.
Lazy instantiation of SqlConnection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ref: [mythz](https://groups.google.com/forum/#!topic/servicestack/bb95kGpDcEo) | |
using System; | |
using System.Configuration; | |
using System.Data; | |
using System.Data.Common; | |
namespace Clear2Pay.OTS.UTP.Data.Tests | |
{ | |
public class Database : IDisposable | |
{ | |
private readonly string _connectionString; | |
private IDbConnection _db; | |
public Database() | |
{ | |
_connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; | |
} | |
public Database(string connectionString) | |
{ | |
_connectionString = connectionString; | |
} | |
public virtual IDbConnection Db | |
{ | |
get | |
{ | |
if (_db == null) | |
{ | |
var providerName = "System.Data.SqlClient"; | |
var factory = DbProviderFactories.GetFactory(providerName); | |
_db = factory.CreateConnection(); | |
if (_db == null) | |
{ | |
throw new Exception("_db is null"); | |
} | |
_db.ConnectionString = _connectionString; | |
_db.Open(); | |
return _db; | |
} | |
return _db; | |
} | |
} | |
public virtual void Dispose() | |
{ | |
if (_db != null) | |
_db.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment