【发布时间】:2017-08-10 09:04:06
【问题描述】:
我正在使用 NHibernate 并且有许多存储库,它们都继承自基础 NHibernateRepository 类。这是我的一个存储库:
public class StaffRepository : NHibernateRepository<IStaff>,
{
public IEnumerable<IStaff> GetBySiteRegionAndMonth(int siteId, int regionId, DateTime firstOfMonth)
{
return Repository.Where(ab => ab.SiteId == siteId && ab.WorkDate >= firstOfMonth && ab.WorkDate < firstOfMonth.AddMonths(1));
}
}
还有基类:
public class NHibernateRepository<TEntity> : IRepository<TEntity> where TEntity : IEntity
{
protected ISession session;
public NHibernateRepository()
{
this.session = new SessionCache().GetSession();
}
public IQueryable<TEntity> Query
{
get
{
return session.Query<TEntity>();
}
}
// Add
public void Add(TEntity entity)
{
session.Save(entity);
}
// GetById
public TEntity GetById(int id)
{
// return session.Load<TEntity>(id);
return this.Query.SingleOrDefault(e => e.Id == id);
}
}
我现在尝试使用不会访问真实数据库的测试类模拟基类NHibernateRepository,而是使用静态列表。这是我在结构映射容器中注册的测试类:
x.For(typeof(IRepository<>)).Use(typeof(TestNHibernateRepository<>));
我的问题是,真正的NHibernateRepository 仍在测试中使用。根据我的注册,我使用的是真实的StaffRepository:
x.For<IStaffRepository>().Singleton().Use<StaffRepository>();
我所有的其他测试类都被很好地注入了,但我认为这是有问题的,因为它是一个继承的类。
如何确保我的 StaffRepository 使用 TestNHibernateRepository 而不是 NHibernateRepository?
【问题讨论】:
标签: nhibernate dependency-injection mocking fluent-nhibernate structuremap