Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Created June 10, 2021 11:12
Show Gist options
  • Save NDiiong/65a0681c61579c072d25845522916d86 to your computer and use it in GitHub Desktop.
Save NDiiong/65a0681c61579c072d25845522916d86 to your computer and use it in GitHub Desktop.
UnitOfWork
public interface IUnitOfWork
{
IRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Type repository = null) where TEntity : class, IEntity<TKey>, new() where TKey : IEquatable<TKey>;
void Save();
Task SaveAsync();
void Dispose();
}
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>();
public UnitOfWork(DbContext dbContext)
{
_context = dbContext;
}
public void Dispose()
{
throw new NotImplementedException();
}
public IRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Type repository = null) where TEntity : class, IEntity<TKey>, new() where TKey : IEquatable<TKey>
{
if (_repositories.Keys.Contains(typeof(TEntity)))
return _repositories[typeof(TEntity)] as IRepository<TEntity, TKey>;
IRepository<TEntity, TKey> repo = null;
if (repository != null)
repo = (IRepository<TEntity, TKey>)Activator.CreateInstance(repository, new object[] { _context });
else
repo = new GenericRepository<TEntity, TKey>(_context);
_repositories.Add(typeof(TEntity), repo);
return repo;
}
public void Save()
{
_context.SaveChanges();
}
public async Task SaveAsync()
{
await _context.SaveChangesAsync();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment