Background:
I have an application that I have nicely separated my interface logic from my middle tier logic which handles the queries to the database. I do a lot of custom sorting and narrowing so I'm not using many SqlDataSources and instead calling a lot of stored procedures with SqlCommands.
背景:我有一个应用程序,它很好地将接口逻辑与中间层逻辑分离开来,中间层逻辑负责处理对数据库的查询。我进行了大量的自定义排序和收缩,所以我没有使用许多sqldatasource,而是使用SqlCommands调用大量存储过程。
I am using Forms Authentication to create protected sub-directories. In the web.config files in the protected directories I have more connection strings that link to users with higher privileged roles.
我正在使用表单验证来创建受保护的子目录。在web。在受保护目录中的配置文件中,我有更多的连接字符串链接到具有更高特权角色的用户。
Question:
Should I share a SqlConnection object in my middle tier to cut out repetitive code, or should I create a new instance for each operation? A shared SqlConnection I could re-instantiate if I need to change connection strings to get access to protected stored procedures. Is there a best practice here?
问题:我应该在中间层*享SqlConnection对象以删除重复代码,还是应该为每个操作创建一个新实例?如果需要更改连接字符串以访问受保护的存储过程,则可以重新实例化共享的SqlConnection。这里有最佳实践吗?
3 个解决方案
#1
11
Don't worry about sharing to conserve resources. .NET will manage this for you, it does connection pooling by default. Write the code to be clear and understandable and let .NET take care of these details.
不要担心共享以节省资源。。net将为您管理这个,它默认为连接池。编写代码要清晰易懂,并让. net处理这些细节。
#2
9
Create as many SqlConnections as you need, as shortly lived as possible, through the using statement:
通过使用语句,尽可能短地创建尽可能多的SqlConnections:
using (var connection = new SqlConnection(...)) {
connection.Open();
...
}
Sql connections are taken from a connection pool, which will automatically manage contention for you.
Sql连接来自一个连接池,该连接池将自动为您管理争用。
See: http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.80).aspx
参见:http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.80). aspx
#3
#1
11
Don't worry about sharing to conserve resources. .NET will manage this for you, it does connection pooling by default. Write the code to be clear and understandable and let .NET take care of these details.
不要担心共享以节省资源。。net将为您管理这个,它默认为连接池。编写代码要清晰易懂,并让. net处理这些细节。
#2
9
Create as many SqlConnections as you need, as shortly lived as possible, through the using statement:
通过使用语句,尽可能短地创建尽可能多的SqlConnections:
using (var connection = new SqlConnection(...)) {
connection.Open();
...
}
Sql connections are taken from a connection pool, which will automatically manage contention for you.
Sql连接来自一个连接池,该连接池将自动为您管理争用。
See: http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.80).aspx
参见:http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.80). aspx