I am working on implementing a repository and unit of work pattern; but instead of putting my unit of work in the controller and having business logic in the controller I am implementing a request/handler to divide this logic. Is there any downside to splitting the unit of work and having my controllers access through the request/handler? See code example below:
Generic Repo:
public class GenericRepository<TEntity> where TEntity : class
{
internal MyContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(MyContext context)
{
this.context = context;
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);
}
The Unit of Work:
public class UnitOfWork : IDisposable
{
private MyContext context = new MyContext();
private GenericRepository<User> userRepository;
public GenericRepository<User> UserRepository
{
get
{
if (this.userRepository == null)
{
this.userRepository = new GenericRepository<User>(context);
}
return userRepository;
}
}
Then I am creating a request/handler for each of my models and instantiating Unit of Work in there:
public class UserRequest
{
private UnitOfWork unitOfWork = new UnitOfWork();
public User GetById(int id)
{ //more business logic would go here in the handlers...
return unitOfWork.UserRepository.GetById(id);
}
The controller will access the request/handlers:
public class HomeController : Controller
{
private UserRequest userRequest = new UserRequest();
public ActionResult Index()
{
var user = userRequest.GetById(1);
ViewBag.UserEmail = user.Email;
return View();
}
Note: there will be multiple request/handlers that are instantiating the unit of work instance. Could this cause issues since unit of work's purpose is to keep the context to one instance?
Thank you in advance for your feedback!