Last active
August 21, 2019 20:07
-
-
Save antdimot/c960add6c5dbada5a7e7ca889bbd6a79 to your computer and use it in GitHub Desktop.
Example of UnitOfWork
This file contains 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
/* UnitOfWork using example | |
using( var context = new UnitOfWork( "db connection string here" ) ) | |
{ | |
var customer = await context.Use<ICustomerRepository>() | |
.GetBySerial( serial ); | |
} */ | |
using Myapp.Core.Util; | |
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Data.SqlClient; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Unity; | |
using Unity.Resolution; | |
namespace Myapp.Core.Data | |
{ | |
public class UnitOfWork : IDisposable | |
{ | |
private bool _disposed = false; | |
private IDictionary<string, object> _repositories; | |
public IDbConnection Connection { get; private set; } | |
public IDbTransaction Transaction { get; private set; } | |
public UnitOfWork( string connString ) | |
{ | |
_repositories = new Dictionary<string, object>(); | |
Connection = new SqlConnection( connString ); | |
Connection.Open(); | |
Transaction = Connection.BeginTransaction(); | |
} | |
public T Use<T>() where T : class | |
{ | |
var typeName = typeof( T ).Name; | |
if( !_repositories.Keys.Contains( typeName ) ) | |
{ | |
var repository = UnityConfig.Container | |
.Resolve<T>( new ResolverOverride[] | |
{ | |
new ParameterOverride( "context", this ) | |
} ); | |
_repositories.Add( typeName, repository ); | |
} | |
return (T)_repositories[typeName]; | |
} | |
public void SaveChanges() | |
{ | |
if( Transaction == null ) | |
{ | |
throw new InvalidOperationException( "Transaction have already been commited. Check your transaction handling." ); | |
} | |
Transaction.Commit(); | |
Transaction = null; | |
} | |
public void Dispose() | |
{ | |
Dispose( true ); | |
GC.SuppressFinalize( this ); | |
} | |
protected virtual void Dispose( bool disposing ) | |
{ | |
if( _disposed ) | |
return; | |
if( disposing ) | |
{ | |
if( Transaction != null ) | |
{ | |
Transaction.Rollback(); | |
Transaction = null; | |
} | |
if( Connection != null ) | |
{ | |
Connection.Close(); | |
Connection = null; | |
} | |
// Free any other managed objects here. | |
// | |
} | |
// Free any unmanaged objects here. | |
// | |
_disposed = true; | |
} | |
~UnitOfWork() | |
{ | |
Dispose( false ); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment