Skip to content

Instantly share code, notes, and snippets.

@mahizsas
Forked from benfoster/gist:6211703
Last active August 29, 2015 13:56
Show Gist options
  • Save mahizsas/8934655 to your computer and use it in GitHub Desktop.
Save mahizsas/8934655 to your computer and use it in GitHub Desktop.
public interface IDbSession
{
IDbConnection Connection { get; }
}
public class SqlSession : IDbSession
{
private static readonly object @lock = new object();
private readonly string connectionString;
private bool isDisposed;
private IDbConnection cn;
public SqlSession(string connectionString)
{
this.connectionString = connectionString;
}
public virtual IDbConnection Connection
{
get
{
if (isDisposed)
{
throw new InvalidOperationException("The connection has been disposed");
}
return GetConnection();
}
}
private IDbConnection GetConnection()
{
if (cn == null)
{
lock (@lock)
{
if (cn == null)
{
cn = new SqlConnection(connectionString);
cn.Open();
}
}
}
return cn;
}
public void Dispose()
{
if (isDisposed)
{
if (cn != null)
{
cn.Dispose();
}
isDisposed = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment