passing DB Connection object to methods(将 DB Connection 对象传递给方法)
问题描述
想知道是否建议将数据库连接对象传递给(到其他模块)或让方法(在其他模块中)负责设置它.我倾向于让方法设置它,以便在使用它之前不必检查连接的状态,并且只需让调用者将任何需要的数据传递给设置连接所需的调用方法.
Was wondering if it is recomended to pass a database connection object around(to other modules) or let the method (in the other module) take care of setting it up. I am leaning toward letting the method set it up as to not have to check the state of the connection before using it, and just having the caller pass any needed data to the calling method that would be needed to setup the connection.
推荐答案
我个人喜欢使用紧密范围的连接;晚点打开它们,使用它们,然后关闭它们(在使用"块中,都在本地方法中).在大多数情况下,连接池将处理重用连接,因此这种方法没有真正的开销.
Personally I like to use tightly scoped connections; open them late, use them, and close them (in a "using" block, all within the local method). Connection pooling will deal with re-using the connection in most cases, so there is no real overhead in this approach.
传递连接的主要优点使用是为了让您可以传递交易;但是,TransactionScope
是在方法之间共享事务的更简单方法.
The main advantage in passing connections used to be so that you could pass the transaction around; however, TransactionScope
is a simpler way of sharing a transaction between methods.
由于这些类是特定于实现的,我会编写每个类来打开它自己的本机事务.否则,您可以使用 ado.net 工厂方法从配置文件(提供程序名称)创建适当的类型.
Since the classes are implementation specific, I'd write each to open it's own native transaction. Otherwise, you can use the ado.net factory methods to create the appropriate type from the config file (the provider name).
这篇关于将 DB Connection 对象传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 DB Connection 对象传递给方法
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01