存储库模式的通用接口继承和类实现
我已经阅读了一些有关约束的内容,并尝试在我的存储库模式中实现它。
我想要类似下面的东西,但无法完全编译它。
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;}
}
I have read a bit about constraints and am trying to implement it in my repository pattern.
I want something like the below but can't quite get it to compile.
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;}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定为什么存储库中有两个类型参数 - 这有什么意义?
*这是使用泛型的 .NET 存储库的经典示例:*
*首先,存储库接口:*
*第二,通用存储库实现(EF 作为示例):*
*然后,特定存储库(每个聚合根应该有一个,并且每个特定存储库都有一个详细说明特定方法的接口):*
用法:
不要过于疯狂地使用泛型 - 您唯一需要的就是限制存储库由封装在存储库后面的实体使用。
我只是使用
where T : class
。其他人使用
where T : IDomainAggregate
或类似的方法来对允许的实体的实际类型施加约束。Not sure why you have two type parameters on the Repository - what is the point?
*Here is the classic example of a .NET Repository using Generics: *
*First, the Repository Interface: *
*Second, the Generic Repository Implementation (EF as the example): *
*Then, the Specific Repository (you should have one per aggregate root, and also an interface for each specific repository detailing specific methods): *
Usage:
Don't go out looking to go too crazy with generics - the only one you need is to constrain the Repository to be used by a entity that is encapsulated behind the Repository.
I simply use
where T : class
.Other's use
where T : IDomainAggregate
or similar, to put constraints on the actual type of entity which is allowed.在这种情况下,我通常有一个实现 IRepository<> 的基本存储库类,并键入基本模型类。
In this situation i usually have a base repo class that implements IRepository<>, and is typed to a base Model class.
试试这个;
Try this;