我试图为我的服务类实现一个通用存储库。但是当我尝试在 Web 层绑定我的 DbConext 时,我需要引用实体框架。
我的DbContext
public partial class SalesDbContext : DbContext, IUnitOfWork
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Activity> Activities { get; set; }
/// <summary>
/// Allows saving changes via the IUnitOfWork interface.
/// </summary>
void IUnitOfWork.Commit()
{
base.SaveChanges();
}
我的IUnitOfWork
public interface IUnitOfWork
{
/// <summary>
/// Saves changes to all objects that have changed within the unit of work.
/// </summary>
void Commit();
}
我的Repository
public class Repository
{
protected IUnitOfWork UnitOfWork { get; set; }
protected SalesDbContext Context
{
get { return (SalesDbContext)this.UnitOfWork; }
}
public Repository(IUnitOfWork unitOfWork)
{
if (unitOfWork == null) throw new ArgumentNullException("unitOfWork");
this.UnitOfWork = unitOfWork;
}
private DbSet<TEntity> GetDbSet<TEntity>() where TEntity : class
{
return this.Context.Set<TEntity>();
}
protected IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class
{
return this.GetDbSet<TEntity>()
.AsEnumerable();
}
protected virtual void SetEntityState(object entity, EntityState entityState)
{
this.Context.Entry(entity).State = entityState;
}
}
最后我的 Ninject 配置
private static void RegisterServices(IKernel kernel)
{
IUnitOfWork unitOfWork = new SalesDbContext();
kernel.Bind<IUnitOfWork>().ToConstant(unitOfWork);
kernel.Bind<IMarketService>().To<MarketService>();
}
问题是 Ninject 想要实体框架的引用,但我不想在这里添加它,它属于数据层。
你认为 DbContext 的 ToConstant 实现会导致问题吗?