-
-
Save mahizsas/8934655 to your computer and use it in GitHub Desktop.
This file contains 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
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