我正在努力实现存储库和工作单元模式;但是我没有将我的工作单元放在控制器中并且在控制器中具有业务逻辑,而是实现了一个请求/处理程序来划分这个逻辑。拆分工作单元并让我的控制器通过请求/处理程序访问是否有任何缺点?请参阅下面的代码示例:
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);
}
工作单位:
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;
}
}
然后我为每个模型创建一个请求/处理程序,并在那里实例化工作单元:
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);
}
控制器将访问请求/处理程序:
public class HomeController : Controller
{
private UserRequest userRequest = new UserRequest();
public ActionResult Index()
{
var user = userRequest.GetById(1);
ViewBag.UserEmail = user.Email;
return View();
}
注意:将有多个请求/处理程序实例化工作单元实例。这会导致问题,因为工作单元的目的是将上下文保留在一个实例中吗?
提前感谢您的反馈!