使用静态方法与数据库交互 - 有任何潜在问题吗?
我正在寻找一个处理 MVC3/.Net 应用程序数据库访问的类。
该类是静态的,并为常见的数据库查询提供了很好的便利方法 - 各种奇怪的东西,例如“GetColumnBValueForColumnA()”,以及更复杂的查询。它针对给定的解决方案和领域进行了很好的分解/优化。
不过,将类视为静态会触发一些忘记的记忆,认为这可能是一个坏主意(也许在多线程的背景下?),我无法摆脱这种感觉。
保持这种类静态是一个好主意,还是应该为每个数据库调用实例化它?
I'm looking at a class handling database access for an MVC3/.Net application.
The class is static, and provides nice convenience methods for common DB queries - all sorts of twiddly stuff like "GetColumnBValueForColumnA()", as well as much more complex queries. It's nicely factored/optimized for the given solution and domain.
Seeing the class as static, though, triggered some half forgotten memory about how this might be a bad idea (maybe in the context of multi-threading?), and I can't shake the feeling.
Is it a good idea to keep this kind of class static, or should I be instantiating it for each database call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您关心应用程序各层之间的弱耦合、这些层的可重用性、独立的单元测试等问题,那么您不应该执行上述任何操作。你应该使用抽象。
如果您不关心这些事情,那么静态方法就可以了。使用静态方法时唯一要小心的是设计它们,使其可重入< /a> 并且不依赖任何共享状态来保证线程安全。在所有情况下,请确保通过将所有 IDisposable 资源(例如数据库连接和命令)包装在 using 语句中来正确处置它们。
If you care about things like weak coupling between the layers of your application, reusability of those layers, unit testing in isolation you shouldn't be doing any of the above. You should be working with abstractions.
If you don't care about those things then static methods are just fine. The only thing to be careful when working with static methods is to design them so that they are reentrant and do not depend on any shared state in order to be thread safe. In all cases make sure to properly dispose all IDisposable resources such as database connections and commands by wrapping them in using statements.
这些不是您唯一的两个选择。
该类不应该是静态的:通过使其静态您放弃了对象的一些重要优势面向编程,却几乎一无所获。
相反,应该通过基于构造函数的依赖注入将它的实例提供给您的控制器。是否为每个请求重新实例化该类,或者最终是否使用单例,将由您的 DI 绑定代码决定。您可以立即更改它。
以下是一些优点:
我还可以继续说下去。静态类会破坏你的灵活性,并且在 99% 的情况下没有实际优势。
These are not your only two options.
The class should not be static: by making it static you relinquish a few important advantages of object-oriented programming, while gaining practically nothing.
Instead, an instance of it should be provided to your controllers via constructor-based dependency injection. Whether the class is re-instantiated for each request or whether you end up using a singleton is then determined by your DI-binding code. You can change it at the drop of a hat.
Here are a couple of advantages:
I could go on. Static classes kill your flexibility and have no practical advantage 99% of the time.