c# - Repository模式的通用接口(interface)继承和类实现

标签 c# generics inheritance c#-4.0 repository

我已经阅读了一些关于约束的内容,并且正在尝试在我的存储库模式中实现它。

我想要像下面这样的东西,但不能完全编译它。

 public interface IRepository<T>
 {
    void GetAllData<T>();
 }

 //This needs to inherit from IRepository
 //T has to be a model class
 //V has to be a class that implements IEmployeeRepo
 public interface IEmployeeRepo<T, V> where V : EmployeeRepo where T : class : IRepository<T>
 {
    void DoSomethingEmployeeRelated();
 }

 //Dont think this inheritance is correct
 public class EmployeeRepo<Employee, this> : IEmployeeRepo
 {


 }

 //My example model class
 public class Employee
 {
     public string Name {get;set;}
 }

最佳答案

不确定为什么在存储库上有两个类型参数 - 这有什么意义?

*这是使用泛型的 .NET 存储库的经典示例:*

*首先是存储库接口(interface):*

public interface IRepository<T> where T : class
{
   T FindSingle(Expression<Func<T,bool>> predicate);
   IQueryable<T> FindAll(); // optional - matter of preference
   void Add(T entity);
   void Remove(T entity);
}

*二、Generic Repository实现(以EF为例):*

public abstract class GenericRepository<T> : IRepository<T>
{
   private IObjectSet<T> _ObjectSet; // get this in via DI (for example)

   public T FindSingle(Expression<T,bool>> predicate)
   {
      return _ObjectSet.SingleOrDefault(predicate);
   }

   // you can figure out how to do the other implementation methods
}

*然后是特定存储库(每个聚合根应该有一个,并且每个特定存储库都有一个详细说明特定方法的接口(interface)):*

public EmployeeRepository : GenericRepository<Employee>, IRepository<Employee>
{
   // all regular methods (Find, Add, Remove) inherited - make use of them
   public Employee FindEmployeeByName(string name)
   {
      return FindAll().SingleOrDefault(x => x.Name == name);
      // or you could do: return FindSingle(x => x.Name == name);    
   }
}

用法:

IRepository<Employee> repository = new EmployeeRepository<Employee>();

不要过分疯狂地使用泛型 - 您唯一需要的是将存储库限制为由封装在存储库后面的实体使用。

我只是使用 where T : class

其他人使用 where T : IDomainAggregate 或类似的方法来限制允许的实体的实际类型。

关于c# - Repository模式的通用接口(interface)继承和类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4781428/

相关文章:

c++ - 虚函数不叫c++

c# - 我们可以使用基类对象访问派生类属性吗?

c# - MVC 5、EF 6 Barebones 无效的列名称 'Model'

c# - 图像c#中的分隔字母

java - 泛型 <? super A> 不允许将 A 的父类(super class)型添加到列表中

方法签名中的 Java 泛型类型不匹配

arrays - swift 3 : Getting error while joining the reversed() array

java - 创建返回子类对象的父类

c# - 跨机器复制网页的简单方法?

javascript - 以编程方式登录网站并提交表单