如何设置内存存储库

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对象的集合,因为存储库将不知道我在运行之前将它提供给哪些类型.
  • 我需要为Query()方法支持LINQ to Objects.假设我可以想出一个存储对象的好方法,这应该像返回存储对象AsQueryable()的数组一样简单.

您如何存储对象以满足上述要求?

Ant*_*lev 5

基础知识很简单:

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的存储库实现.