First sorry if this was asked already but i cannot find an answer for this 'particular case'.
I've a Interface of Unit of Work:
public interface IUnitOfWork
{
DbContext Context { get; set; }
void Dispose();
void Save();
}
And use a Generic Repository class:
public class GenericRepository<TEntity> where TEntity : class
{
private DbSet<TEntity> dbSet;
private IUnitOfWork UnitOfWork { get; set; }
private DbContext context { get { return UnitOfWork.Context; } }
public GenericRepository(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
I don't want to do my logic in my MVC controler, so I added a businesslayer. My question is, where should I instantiate (and dispote) my IUnitOfWork, in my controler and pass it to my business layer? Example:
public static class CircleLogic
{
public static void DeleteCircle(IUnitOfWork uow, int id)
{
try
{
var circleRep = new GenericRepository<Circle>(uow);
var circle = circleRep.GetByID(id);
......
circleRep.Delete(id);
uow.Save();
}
catch (Exception ex)
{
throw;
}
}
}
I've seen this but I don't want to instantiate it in my business layer. What is the best approach?
Thanks!