說我有下面的實現:MVC通用存儲庫工作模式/股 - 擴展的存儲庫
//Generic repository.
public interface IRepository<T> where T : class {
void Insert(T entity);
void Delete(int id);
void SaveChanges();
//..more generic functions
}
//Repository implementation.
public class EFRepository<T> : IRepository<T> where T: class {
private MyDbContext context;
protected DbSet<T> dbSet;
public EFRepository(): this(new MyDbContext()){}
public EFRepository(MyDbContext context)
{
this.context = context;
dbSet = context.Set<T>();
}
public void Insert(T entity)
{
dbSet.Add(entity);
}
public void Delete(int id)
{
dbSet.Remove(dbSet.Find(id));
}
public void SaveChanges()
{
context.SaveChanges();
}
//...more generic implementations
}
//Unit of Work Interface
public interface IUnitOfWork: IDisposable
{
IRepository<EntityA> ARepository { get; }
IRepository<EntityB> BRepository { get; }
//...more stuff
}
//Unit of Work Implementation
public class EFUnitOfWork: IUnitOfWork
{
private MyDbContext context = new MyDbContext();
private IRepository<EntityA> aRepository;
private IRepository<EntityB> bRepository;
public IRepository<EntityA> ARepository
{
get
{
if (this.aRepository == null)
this.aRepository = new EFRepository<EntityA>(context);
return this.aRepository;
}
}
public IRepository<EntityB> BRepository
{
get
{
if (this.bRepository == null)
this.bRepository = new EFRepository<EntityB>(context);
return this.bRepository;
}
}
//...more stuff
}
最後,我在我的解析器以下綁定:
kernel.Bind(typeof(IRepository<>)).To(typeof(EFRepository<>));
kernel.Bind(typeof(IUnitOfWork)).To(typeof(EFUnitOfWork));
現在,我的問題是......我將如何去擴展EntityA的存儲庫,使其具有更多的操作而不僅僅是通用的操作?
我會後我有幾個那麼遠,
編輯:這是我到目前爲止有:
//New interface.
public class IEntityARepository : IRepository<EntityA>
{
void DoSomethingSpecificToEntityA();
}
//New implementation.
public class EFEntityARepository : EFRepository<EntityA>
{
public EFEntityARepository(MyDbContext context) : base(context) {}
//add additional methods for EntityA
public void DoSomethingSpecificToEntityA()
{
}
}
//Modify Unit of Work Interface as follows.
//Unit of Work Interface
public interface IUnitOfWork: IDisposable
{
IEntityARepository ARepository { get; }
IRepository<EntityB> BRepository { get; }
//...more stuff
}
//Modify Unit of Work Implementation as follows.
public class EFUnitOfWork: IUnitOfWork
{
private MyDbContext context = new MyDbContext();
private IEntityARepository aRepository;
private IRepository<EntityB> bRepository;
public IEntityARepository ARepository
{
get
{
if (this.aRepository == null)
this.aRepository = new EFEntityARepository<EntityA>(context);
return this.aRepository;
}
}
public IRepository<EntityB> BRepository
{
get
{
if (this.bRepository == null)
this.bRepository = new EFRepository<EntityB>(context);
return this.bRepository;
}
}
//...more stuff
}
添加以下綁定:
kernel.Bind(typeof(IEntityARepository)).To(typeof(EFEntityARepository));
但是,我確定這是不正確的。或者至少,不是正確的做法。
就是這樣嗎?我是否也不需要對工作單元進行更改? – Seriphos
查看上面的編輯,我想你只需要返回派生類的一個實例。 –
如果您看到我的原始帖子的編輯,我的新實現已經有了。但似乎我已經添加/修改了比我需要的更多東西。 – Seriphos