具体通用接口
我正在重构所有各种类型的存储库接口。它们中的大多数都包含非常相似的方法,例如 Add、Update,但有些方法仅对特定类型有意义。这是一个最佳实践问题。
我考虑过使用泛型来解决问题。
public interface IRepository<T>
{
T Get(int id);
void Add(T x);
}
但现在来说说具体方法。我当然可以对接口进行“子类化”,但是这样我的情况并不比以前更好。我会有这样的代码:
IUserRepository<User> users;
一种巧妙的方法是,如果我可以有多个约束,例如:
public partial interface IRepository<T>
{
T Get(int id);
void Add(T x);
}
public partial interface IRepository<T> where T: User
{
T Get(Guid id);
}
public partial interface IRepository<T> where T: Order
{
T Get(string hash);
}
但编译器抱怨继承冲突。另一种方法是对方法进行限制:
public partial interface IRepository<T>
{
T Get(int id);
void Add(T x);
T Get(Guid id) where T: User;
T Get(string hash) where T: Order;
}
但这并不是这些方法的工作方式。当然,编译器无法理解我的意图,并且想要该方法的类型定义。
现在我只有抛出 NotImplemented 的方法。丑陋的。
我正在寻找一个能让我踢自己的解决方案。
I'm refactoring all my repository interfaces of various types. Most of them contain very similar methods like Add, Update but some have methods which only makes sense for a specific type. This is a best practices question.
I thought about using generics to straighten things up.
public interface IRepository<T>
{
T Get(int id);
void Add(T x);
}
But now for the specific methods. I could ofcourse "subclass" the interface, but then I'm not better off than before. I would have code like:
IUserRepository<User> users;
One neat way would be if I could have multiple constraints like:
public partial interface IRepository<T>
{
T Get(int id);
void Add(T x);
}
public partial interface IRepository<T> where T: User
{
T Get(Guid id);
}
public partial interface IRepository<T> where T: Order
{
T Get(string hash);
}
But the compiler complains about conflicting inheritance. Annother way would be contraints on the methods:
public partial interface IRepository<T>
{
T Get(int id);
void Add(T x);
T Get(Guid id) where T: User;
T Get(string hash) where T: Order;
}
But that's not quite the way these this work is it. Compiler fathoms not my intentions and wants a type definition on the method, of course.
Right now I just have methods that throw NotImplemented. Ugly.
I'm looking for a solution that will make me kick myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是我对类似问题的想法:
为每个对象创建通用存储库与特定存储库相比有何优势?
要点是域通常无法通用,需要另一种方法。我给出了一个使用特定于域的接口但具有通用基类的示例。
Here are my thoughts on a similar question:
Advantage of creating a generic repository vs. specific repository for each object?
The gist is that domains often can't be generalized, and another approach is in order. I give an example of using domain-specific interfaces but with a generalized base class.