using System; using System.Collections.Generic; using System.Data.Common; using System.IO; using System.Reflection; namespace Mesnac.Codd.Session { public class DbSession : IDisposable { public DbSession(DbProviderFactory factory, string connstr) { this.ConnectionString = connstr; this.ProviderFactory = factory; } public string ConnectionString { get; set; } public DbProviderFactory ProviderFactory { get; set; } private DbConnection _connection = null; public DbConnection Connection { get { if (_connection == null) { this._connection = this.ProviderFactory.CreateConnection(); this._connection.ConnectionString = this.ConnectionString; } return _connection; } } private DbCommand _command = null; public DbCommand Command { get { if (_command == null) { this._command = this.ProviderFactory.CreateCommand(); this._command.Connection = this.Connection; this._command.CommandType = System.Data.CommandType.Text; } return _command; } } public void Close() { try { this.Connection.Close(); this.Connection.Dispose(); this.Command.Dispose(); } catch { } finally { this._connection = null; this._command = null; } } public void Dispose() { this.Close(); this.ProviderFactory = null; } } public static class DbSessionFactory { private static Dictionary dbSessionFactoryList = new Dictionary(); public static DbSession GetDbSession(string connectionString) { DbSession session = null; if (!dbSessionFactoryList.TryGetValue(connectionString, out session)) { DbProviderFactory factory = System.Data.SqlClient.SqlClientFactory.Instance; session = new DbSession(factory, connectionString); dbSessionFactoryList.Add(connectionString, session); } return session; } } }