私はリポジトリと作業単位パターンの実装に取り組んでいます。ただし、作業単位をコントローラーに配置してコントローラーにビジネスロジックを配置する代わりに、このロジックを分割するリクエスト/ハンドラーを実装しています。作業単位を分割し、リクエスト/ハンドラーを介してコントローラーにアクセスさせることにマイナス面はありますか? 以下のコード例を参照してください。
汎用レポ:
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;
}
}
次に、モデルごとにリクエスト/ハンドラーを作成し、そこで Unit of Work をインスタンス化します。
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();
}
注: 作業単位インスタンスをインスタンス化する複数の要求/ハンドラーが存在します。作業単位の目的はコンテキストを 1 つのインスタンスに保持することであるため、これにより問題が発生する可能性はありますか?
フィードバックをお寄せいただきありがとうございます。