.NET 1.1 的存储库模式
将存储库模式与 .NET 1.1 (C#) 一起使用的典型方法是什么?
我正在寻找类似的东西 这个 Stack Overflow 问题,除了在 .NET 1.1 中,我没有泛型,所以我只是想看看它是否可能(我确信它是),以及它通常是如何完成的。
What is a typical approach to using the repository pattern with .NET 1.1 (C#)?
I'm looking for something along the lines of this Stack Overflow question, except that in .NET 1.1, I don't have generics, so I'm just looking to see if it's possible (I'm sure it is), and how it's typically done.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非我误读了某些内容,否则您链接的问题中接受的答案不使用泛型。 他正在定义一个接口,并使用术语“通用”来表示该接口不直接绑定到模型中的任何特定表。
unless I misread something, the accepted answer in the question you linked doesn't use generics. He is defining an Interface and using the term "generic" to mean the Interface isn't tied directly to any specific table in the model.
这是很有可能的,但您要么必须不使用通用接口,要么必须进行大量转换。 使用接口...
这工作正常,但调用代码必须将对象转换为正确的类型,并且具体实现中的方法必须检查类型并引发异常。 直接转换要求运行时异常,因此我会避免这种方法。
我建议的方法是不要让您的存储库实现通用接口。 相反,让他们按照约定实现通用命名的方法。
编辑添加:我重新阅读了链接的答案。 最后一段完整的内容让我不知所措,但我可以对使用 DI 进行一些扩展。 在大多数情况下,使用 DI 注入“通用”(在本例中意味着从公共接口派生)存储库是没有意义的。 除了通用方法之外,存储库还将具有特定于实体的方法,例如 GetCustomersWithPastDueAccounts 。 您可以使用该方法定义 ICustomerRepository 并让您的 CustomerRepository 实现该方法。 然后,您可以使用依赖项注入在运行时注入 CustomerRepository。 这没有什么问题,但根据我的经验,一个存储库的多个实现是相当罕见的,因此这样做没有什么意义。
It's very possible but you either have to not use a common interface or do a lot of casting. Using an interface ...
This works fine but calling code has to cast objects to the correct type and methods in concrete implementations have to check type and throw exceptions. Direct casting is asking for runtime exceptions so I would avoid this approach.
The approach I would recommend is to not have your repositories implement a common interface. Instead have them implement commonly named methods by convention.
Edited to add: I reread the linked answer. The last full paragraph loses me but I can expand a bit on using DI. In most cases it wouldn't make sense to use DI to inject a "generic" (in this case meaning derived from a common interface) repository. In addition to the common methods, a repository will have entity specific methods such as
GetCustomersWithPastDueAccounts
. You could define an ICustomerRepository with that method and have your CustomerRepository implement that. Then you could use dependency injection to inject CustomerRepository at runtime. There's nothing wrong with that, but in my experience it's fairly rare that you would have multiple implementations of a repository so there's little point in doing so.