/// <summary> /// Creates and returns a unit of work to the caller. /// If a unit of work is already being used, throws an exception. /// Allows only one instance of unit of work to exist. /// </summary> /// <returns></returns> public virtual IUnitOfWork GetUnitOfWork() { if (_UnitOfWork != null) throw new Exception("a unit of work is already in use."); else { //If we are not responsible for keeping connection open, //then create and return a unit of work if (!KeepConnectionAlive) { _Context = new EFDbContext(DatabaseName); if (_FirstRequest) { _Context.Database.Initialize(force: false); _FirstRequest = false; } } else { //We need to create a dbconnection and keep it running. //Type of dbconnection depends on the db engine we are using //SqlConnection for SqlServer, SqlCeConnection for CE if (_DbConnection == null) { string connectionString = null; if (DisableSqlCe) { //Using SqlServer _DbConnection = new SqlConnection(); //localDb string //connectionString = "Server=(localdb)\\v11.0;Integrated Security=true;"; //"Server=(localdb)\\Test;Integrated Security=true;AttachDbFileName= myDbFile;" connectionString = @" Server=.\SQLEXPRESS; Database=" + DatabaseName + "; Trusted_Connection=true"; } else { //Using SqlCe _DbConnection = new SqlCeConnection(); connectionString = "Data Source=" + DatabaseName; } //Create a context and initialize the db on startup. if (_FirstRequest) { using (var tempContext = new EFDbContext(connectionString)) { tempContext.Database.Initialize(force: false); } _FirstRequest = false; } _DbConnection.ConnectionString = connectionString; _DbConnection.Open(); } _Context = new EFDbContext(_DbConnection, false); } _UnitOfWork = new UnitOfWork(_Context); return _UnitOfWork; } }
/// <summary> /// Closes a previously created unit of work and disposes the underlying resources. /// If no context was created, throws an exception. /// </summary> public virtual void ReturnUnitOfWork() { if (_UnitOfWork != null) { //If we do not own the connection, it should be already closed/ if (!KeepConnectionAlive) { if (_DbConnection != null) throw new Exception("Database connection is not null in disconnected state."); } else if (_DbConnection == null || _DbConnection.State != System.Data.ConnectionState.Open) throw new Exception("Database connection is not open in connected state."); //disposes dbcontext as well. _UnitOfWork.Dispose(); _UnitOfWork = null; _Context = null; } }