gjk
gjk

Reputation: 7

Global SqlConnection

I have a Web Service that requires an SqlConnection. There are 5 web methods that use this SqlConnection, but presently they are declared (locally) in each of the methods. Would it be acceptable to make it a global variable in this case?

Thanks

Upvotes: 0

Views: 827

Answers (3)

lsalamon
lsalamon

Reputation: 8174

Unless you need very high performance, open and close each connection at each use. The IIS or system does the rest for you. Simple and efficient.

Upvotes: 0

Joe White
Joe White

Reputation: 97676

No.

According to the documentation for SqlConnection:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Since your different web methods could be called simultaneously from different threads, you'd better not share the same connection instance between them.

The typical pattern is that every time you need a database connection, you create a new instance, and Dispose it as soon as you're done. Threading is one of the reasons. Connection pooling makes sure it's not too expensive to create all those connection instances.

Upvotes: 3

Not Available
Not Available

Reputation: 3355

What if you ever need a second connection ?

I'd suggest passing the variable around between classes/functions optionally putting it as class members.

Upvotes: 0

Related Questions