Created
October 10, 2019 21:30
-
-
Save Rudyzio/5635fc79c052d1789efbbffeabd64438 to your computer and use it in GitHub Desktop.
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 : IDisposable | |
{ | |
IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity; | |
int Complete(); | |
} | |
public class UnitOfWork : IUnitOfWork | |
{ | |
private readonly ApplicationDbContext _context; | |
private Hashtable _repositories; | |
public UnitOfWork(ApplicationDbContext context) | |
{ | |
_context = context; | |
} | |
public int Complete() | |
{ | |
return _context.SaveChanges(); | |
} | |
public IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity | |
{ | |
if (_repositories == null) | |
_repositories = new Hashtable(); | |
var type = typeof(TEntity).Name; | |
if (!_repositories.ContainsKey(type)) | |
{ | |
var repositoryType = typeof(Repository<>); | |
var repositoryInstance = | |
Activator.CreateInstance(repositoryType | |
.MakeGenericType(typeof(TEntity)), _context); | |
_repositories.Add(type, repositoryInstance); | |
} | |
return (IRepository<TEntity>)_repositories[type]; | |
} | |
public void Dispose() | |
{ | |
_context.Dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment