Created
September 2, 2013 11:59
-
-
Save danmusk/6412120 to your computer and use it in GitHub Desktop.
Glimpse ADO Dapper Ninject SqlServer
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 class DbConnectionBindings : NinjectModule | |
{ | |
public override void Load() | |
{ | |
Bind<MySpesificDatabaseConnection>() | |
.ToSelf() | |
.InRequestScope() | |
.WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["MyConnectionStringInConfig"].ConnectionString) | |
.OnDeactivation(con => con.Close()) | |
.OnActivation(con => con.Open()); | |
} | |
} | |
public class MySpesificDatabaseConnection : BaseConnection | |
{ | |
public MySpesificDatabaseConnection(string connectionString) | |
: base(connectionString) | |
{ | |
} | |
} | |
public abstract class BaseConnection : IDbConnection | |
{ | |
private readonly IDbConnection _dbConnection; | |
protected BaseConnection(string connectionString) | |
{ | |
if (string.IsNullOrEmpty(connectionString)) | |
throw new ArgumentNullException("connectionString", "ConnectionString can not be null"); | |
var factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); | |
var conn = factory.CreateConnection(); | |
if (conn == null) | |
throw new Exception("Could not create databaseconnection"); | |
conn.ConnectionString = connectionString; | |
_dbConnection = conn; | |
} | |
public void Dispose() | |
{ | |
_dbConnection.Dispose(); | |
} | |
public IDbTransaction BeginTransaction() | |
{ | |
return _dbConnection.BeginTransaction(); | |
} | |
public IDbTransaction BeginTransaction(IsolationLevel il) | |
{ | |
return _dbConnection.BeginTransaction(il); | |
} | |
public void Close() | |
{ | |
_dbConnection.Close(); | |
} | |
public void ChangeDatabase(string databaseName) | |
{ | |
_dbConnection.ChangeDatabase(databaseName); | |
} | |
public IDbCommand CreateCommand() | |
{ | |
return _dbConnection.CreateCommand(); | |
} | |
public void Open() | |
{ | |
_dbConnection.Open(); | |
} | |
public string ConnectionString | |
{ | |
get { return _dbConnection.ConnectionString; } | |
set { _dbConnection.ConnectionString = value; } | |
} | |
public int ConnectionTimeout | |
{ | |
get { return _dbConnection.ConnectionTimeout; } | |
} | |
public string Database | |
{ | |
get { return _dbConnection.Database; } | |
} | |
public ConnectionState State | |
{ | |
get { return _dbConnection.State; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment