在存储库中传递规范对象是否太过分了
在存储库中传递规范对象是否太过分了
我问这个问题是因为,如果我们在像 FindCustomersCreatedToday 这样的方法中传递规范对象,
class CustomerRepository
{
public List<Customer> FindCustomersCreatedToday(ISpecification ISCreatedToday)
{
List<Customer> customers= Load all customers from db;
List<Customer> newList=new List<>();
foreach(var customer in customers)
{
if(ISCreatedToday.SatisfiedBy(customer)
{
newList.Add(customer);
}
}
}
}
我在我看到的大多数网站中都实现了上面的实现,它们会从数据库中获取所有实体,并且循环遍历它们并将它们传递到规范中,但我不喜欢立即加载所有实体然后创建新的过滤列表的想法。
假设我有 10000 个客户,但只有 10 个通过了这个标准。
这不是为了通过规范而过度杀戮吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,如果你期望有很多顾客,这绝对是多余的。您可以使用规范实例中的信息来生成适当的 SQL/HQL 或 ICreteria(假设您使用 NHibernate)。
该代码的表达能力比您发布的代码稍差,但它仍然擅长捕获规范中的一些域信息。
使用规范时要记住的一件事是它是一个领域概念。它属于领域层,应该不受数据访问技术的影响。获取数据的技术很重要,但在领域层并不重要,它们属于数据访问层。在我看来,像
Expression>
这样的东西是域代码的“基础设施”。此外,基于 Linq 的规范往往要求域对象将其数据公开为属性,这有时会破坏其封装。因此,整个事情可能会变成“Linq over 贫血模型”。我强烈建议您阅读DDD 书籍。它有一章专门讨论规范模式和您正在处理的所有权衡。
Yes it is definitely an overkill if you expect a lot of customers. You can use information in the instance of your specification to generate appropriate SQL/HQL or ICreteria (assuming you use NHibernate).
This code is bit less expressive than the one you posted but it still good at capturing some domain information in Specification.
One thing to keep in mind when you work with Specification is that it is a domain concept. It belongs to domain layer and should be free of data access technologies. Technicalities of getting the data are important they just not important in domain layer, they belong to data access layer. Things like
Expression<Func<Customer, bool>>
are to 'infrastructural' for domain code in my opinion. In addition, Linq-based specification tend to require domain objects to expose their data as properties which sometimes breaks their encapsulation. So the whole thing may turn into "Linq over Anemic Model".I highly recommend you to read DDD book. It has a chapter dedicated to Specification pattern and all the tradeoffs that you are dealing with.
正如 Ayende 在他的 N层应用审核,如果你需要规范模式,LINQ是你应该使用的规范技术。它的优点是可以转换为 SQL 或 HQL 或任何其他查询语言,因此可以在数据源上执行表达为
Expression>
的规范,而无需下载所有数据。As Ayende pointed in his N-layer app review, LINQ is the specification technology you should use if you need specification pattern. It has an advantage of being convertible to SQL or HQL or any other query language so specifications expressed as
Expression<Func<T, bool>>
can be executed on the datasource without having to download all the data.