Created
January 23, 2012 16:40
-
-
Save stevenkuhn/1664157 to your computer and use it in GitHub Desktop.
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
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); | |
} | |
} |
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
private static void RegisterServices(IKernel kernel) | |
{ | |
var connectionString = | |
ConfigurationManager.ConnectionStrings["Database"].ConnectionString; | |
kernel.Bind<IDbContext>().To<SqlContext>() | |
.InRequestScope() | |
.WithConstructorArgument("connectionString", connectionString); | |
} |
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
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