单例 DAL 类
DAL (customerDAL) 中的类不应该是单例吗? 由于我的控制器 (customerController) 公开了“Shared Subs”,因此在每次调用时,无需创建新的 DAL 对象(如果已存在)。 正确的?
谢谢
Shouldn't classes in DAL (customerDAL) be singleton? Since my controllers (customerController) exposes "Shared Subs", then on every call, there is no need to create a new DAL object if already existed. Correct?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
众所周知,单例对象很难测试。 我会考虑以这样一种方式创建 DAL:实例化然后根据需要创建一个新的 DAL 并不昂贵。 通过这种方式,您将能够更轻松地为 DAL 编写单元测试,并且仍然不会产生太多开销。 此外,如果您将 DAL 创建为单例,并且在多线程环境(例如 Web 应用程序)中使用它,则需要更加关注使其线程安全。
Singleton objects are notoriously hard to test. I would look at creating your DAL in such a way that it isn't expensive to instantiate and then creating a new one as needed. This way you'll be able to write unit tests for DAL much more easily and still not incur much overhead. Additionally, if you create the DAL as a singleton, you'll need to be much more concerned with making it thread-safe if you use it in a multi-threaded environment (such as a web app).
如果您有一个网站,单例 dal 对象非常危险,因为对该网站的每个请求都是同一应用程序的一部分。 如果构建错误,它们可能会成为访问数据库的瓶颈。
If you have a web site singleton dal objects are very dangerous because every request to the site is part of the same application. If you build them wrong, they can become bottlenecks for access to the database.
它在很大程度上取决于完整解决方案的架构。 当你有很多消费者时,一个单身人士可能会很难获得。 此处 是设计 DAL 时可能需要考虑的事项的清单。 此外,还有许多 DAL 模式(例如存储库)和一些类似外观的模式。
It highly depends on the architecture of your complete solution. One singleton may play hard to get when you have many consumers. Here is a checklist of things you may want to consider when designing DAL. Also, there are lots of DAL patterns like Repository and some facade like patterns.
仅当您希望确保在应用程序的实例中只实例化一个类的一个实例时,才应使用 Singleton。
Singleton 几乎不能被视为代码味道。 大多数使用 Singleton 的人都用得很不好。 因此,当你看到它时,很有可能它没有被正确使用。
对于 DAL,对象的创建并不复杂。 他们应该依赖于使用连接池,然后在每次需要执行命令时从池中请求连接。
当然,有不同的模式可用,您应该主要使用 ORM,除非需要调整请求以提高性能。
请参阅 NHibernate、SubSonic,Linq2Sql,实体框架(尚未发布?)等。
Singleton should only be used when you want to make sure only one instance of a class is ever instantiated inside an instance of your application.
Singleton could barely be considered a Code Smell. Most of the people who use Singleton uses it badly. Therefor, when you see one there is a great chance that it's not used properly.
As for the DAL, objects are not expansive to create. They should rely on using a connection pool and then request a connection from the pool every time a command need to be executed.
Of course, there is different patterns available and you should mostly use an ORM unless the request needs to be tweaked for performance.
See NHibernate, SubSonic, Linq2Sql, Entity Framework (yet to be released?), etc.