Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created August 12, 2013 15:14
Show Gist options
  • Save benfoster/6211703 to your computer and use it in GitHub Desktop.
Save benfoster/6211703 to your computer and use it in GitHub Desktop.
Dapper Session Per Request
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