Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- First we implement everything explicitly using `private IDbConnection Connection;` to perform all the actions. It's a bit cumbersome, but it's OK, we just really need to do it once:
- public class UnityConnection : IDbConnection
- {
- private readonly UnityContainer _unityContainer;
- public UnityConnection() : this("abc") { }
- public UnityConnection(string connectionStringName)
- {
- var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
- Connection = new MySqlConnection(connectionString);
- Connection.Open();
- _unityContainer = new UnityContainer();
- _unityContainer.RegisterInstance<IDbConnection>(Connection);
- }
- private IDbConnection Connection;
- #region "IDbConnection implementation"
- public string ConnectionString
- {
- get
- {
- return Connection.ConnectionString;
- }
- set
- {
- Connection.ConnectionString = value;
- }
- }
- public int ConnectionTimeout
- {
- get
- {
- return Connection.ConnectionTimeout;
- }
- }
- public string Database
- {
- get
- {
- return Connection.Database;
- }
- }
- public ConnectionState State
- {
- get
- {
- return Connection.State;
- }
- }
- public IDbTransaction BeginTransaction()
- {
- return Connection.BeginTransaction();
- }
- public IDbTransaction BeginTransaction(IsolationLevel il)
- {
- return Connection.BeginTransaction(il);
- }
- public void ChangeDatabase(string databaseName)
- {
- Connection.ChangeDatabase(databaseName);
- }
- public void Close()
- {
- Connection.Close();
- }
- public IDbCommand CreateCommand()
- {
- return Connection.CreateCommand();
- }
- public void Dispose()
- {
- Connection.Dispose();
- }
- public void Open()
- {
- Connection.Open();
- }
- #endregion
- }
- Then the implementation of the repository would be:
- public class FooRepository<T> where T : IDisposable, IDbConnection, new()
- {
- private readonly IDbConnection _connection;
- public FooRepository() : this(new T()) { }
- public FooRepository(IConnection connection)
- {
- _connection = connection;
- }
- public List<string> GetBar()
- {
- // ...
- }
- public void Dispose()
- {
- _connection.Dispose();
- }
- }
- ...and it can be called as:
- var repo1 = new FooRepository<UnityConnection>();
- var repo2 = new FooRepository<UnityConnection>(new UnityConnection("xyz"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement