将 DB Connection 对象传递给方法

passing DB Connection object to methods(将 DB Connection 对象传递给方法)
本文介绍了将 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 对象传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)