Skip to content

Instantly share code, notes, and snippets.

@stevenkuhn
Created January 23, 2012 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenkuhn/1664157 to your computer and use it in GitHub Desktop.
Save stevenkuhn/1664157 to your computer and use it in GitHub Desktop.
using Dapper;
public class EmployeeController : Controller
{
private IDbContext DbContext { get; set; }
public EmployeeController(IDbContext dbContext)
{
DbContext = dbContext;
}
[HttpGet]
public ActionResult Index()
{
var employees = DbContext.GetConnection().Query("SELECT * FROM Employees");
return View(employees);
}
}
private static void RegisterServices(IKernel kernel)
{
var connectionString =
ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
kernel.Bind<IDbContext>().To<SqlContext>()
.InRequestScope()
.WithConstructorArgument("connectionString", connectionString);
}
public interface IDbContext
{
IDbConnection GetConnection();
}
public class SqlContext : IDbContext, IDisposable
{
private readonly string ConnectionString;
private static readonly object @lock = new object();
private SqlConnection Connection;
public SqlContext(string connectionString)
{
ConnectionString = connectionString;
}
public IDbConnection GetConnection()
{
if (Connection == null)
{
lock (@lock)
{
if (Connection == null)
{
Connection = new SqlConnection(ConnectionString);
Connection.Disposed += new EventHandler(Connection_Disposed);
Connection.Open();
}
}
}
return Connection;
}
void Connection_Disposed(object sender, EventArgs e)
{
Connection = null;
}
public void Dispose()
{
if (Connection != null)
{
lock (@lock)
{
if (Connection != null)
{
Connection.Dispose();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment