Chr*_*ris 5 c# design-patterns
我有以下课程:
public class InMemoryRepository : IRepository
{
public void Add(object entity)
{
throw new NotImplementedException();
}
public void Attach(object Entity)
{
throw new NotImplementedException();
}
public T Get<T>(object id)
{
throw new NotImplementedException();
}
public IList<T> GetAll<T>(string queryName)
{
throw new NotImplementedException();
}
public IList<T> GetAll<T>()
{
throw new NotImplementedException();
}
public IQueryable<T> Query<T>()
{
throw new NotImplementedException();
}
public void Remove(object entity)
{
throw new NotImplementedException();
}
public void Save(object entity)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
我们的默认存储库实现使用NHibernate作为后备存储,但我想实现它的内存版本,这样我就可以对域对象进行原型设计,而无需创建支持SQL数据库.假设所有对象都具有Id属性作为主键的约定,您将如何为此实现通用内存存储?
一些关键点我很难解决:
Get<TestEntity>(object id)应该能够查询所有存储的TestEntity实例并找到具有匹配Id属性的实例,但是我无法直接定义TestEntity对象的集合,因为存储库将不知道我在运行之前将它提供给哪些类型.您如何存储对象以满足上述要求?
基础知识很简单:
public class InMemoryRepository : IRepository
{
private readonly IList<object> entities = new List<object>();
public T Get<T>(object id)
{
return entities.OfType<T>.SingleOrDefault(e => e.ID == id);
}
public IList<T> GetAll<T>()
{
return entities.OfType<T>.ToList();
}
public IQueryable<T> Query<T>()
{
return GetAll<T>.AsQueryable();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,一旦涉及到public IList<T> GetAll<T>(string queryName),事情变得复杂.
您可以在测试中使用基于SQLite的存储库实现.