具有通用接口和EF中的DI的存储库模式

时间:2014-10-07 05:57:55

标签: c# generics dependency-injection repository-pattern

我有这个现有的代码

public interface IRepository<T>
{
    void Create(T obj);
    T Retrieve(string key);
}


public class ItemRepository : IRepository<Item>
{
        public void Create(Item obj)
        {
            //codes
        }

        public Item Retrieve(string key)
        {
            //codes
        }    
}

我想创建一个通用类存储库,其中我必须向构造函数注入一种类型的IRepository,然后使用它自己的方法实现。我已经有一个现有的代码,但它目前是错误的

    public class Repository
{
    IRepository<T> action = null;
    public Repository(IRepository<T> concreteImplementation)
    {
        this.action = concreteImplementation;
    }

    public void Create(T obj)
    {
        action.Create(obj);
    }
}

这些课程来自EF。如果没有解决这个问题的最佳方法呢?

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要一个可以通过委托特定类型的存储库实现来创建或检索任何类型对象的存储库吗?

你觉得这个怎么样?您定义了此Repository类,但您必须创建实际存储库的具体实现才能使用它,然后仍然必须创建Repository的实例。为什么不使用你必须创建的通用实现呢?

那你的Retrieve方法怎么样?这将如何在你的Repository课程中看到?你会回来Object吗?或者你会使你的方法通用吗?

无论如何要回答你的问题,我想你可以这样做:

public class Repository
{
    IRepository action = null;
    public Repository(IRepository concreteImplementation)
    {
        this.action = concreteImplementation;
    }

    public void Create<T>(T obj)
    {
        action.Create(obj);
    }
}

但是你必须引入一个非泛型接口,因为你不需要在构造函数中使用带泛型参数的接口而不在类上指定泛型类型。

public interface IRepository
{
    void Create(object obj);
    object Retrieve(string key);
}

或者您可以将类型传递给Create方法,而不是使用通用参数:

public class Repository
{
    IRepository action = null;
    public Repository(IRepository concreteImplementation, Type respositoryType)
    {
        this.action = concreteImplementation;
        expectedType=repositoryType;
    }

    public void Create(Type type, Object obj)
    {
        if(type==expected && obj.GetType()==type)
        {
            action.Create(obj);
        }
    }
}

但这两个都是可怕的想法。只需使用泛型并为每种类型创建一个存储库,从长远来看它将是最好的

答案 1 :(得分:0)

我认为您可能只是在通用存储库类的上下文中缺少T的定义。

尝试像这样添加<T>

public class Repository<T>
{
  ...
}
相关问题