Created
June 10, 2021 11:12
-
-
Save NDiiong/65a0681c61579c072d25845522916d86 to your computer and use it in GitHub Desktop.
UnitOfWork
This file contains hidden or 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
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(); | |
} |
This file contains hidden or 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
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