Skip to content

Instantly share code, notes, and snippets.

@Rudyzio
Created October 10, 2019 21:30
Show Gist options
  • Save Rudyzio/5635fc79c052d1789efbbffeabd64438 to your computer and use it in GitHub Desktop.
Save Rudyzio/5635fc79c052d1789efbbffeabd64438 to your computer and use it in GitHub Desktop.
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