سؤال

Could I store a SqlConnection in the HttpContext? I mean, how can I share a single SqlConnection across multiple classes?

In my project every class inherits a base abstract class that open and close connection. This class recognizes if a SqlConnection was opened by another class in that case uses it.

I can store this connection in another way that isn't HttpContext? There is another method to do this, exp. pass the connection between layers?

THX

هل كانت مفيدة؟

المحلول

I wonder why you need to store a single SqlConnection. It doesn't smell great.

If you really do need to share a single SqlConnection across multiple classes, dependency injection is likely a better option. Have a connection factory instantiate a connection object and pass it around as required.

Otherwise, let the DBMS worry about controlling your connection resources. Create, open and close a connection each time you need one.

نصائح أخرى

You are going wrong way. You shouldn't follow this thinking unless you need to share transaction context as mentioned by Lasse V. Karlsen mentioned in his comment. If you are worried about performance and thi is the reason why you want to keep one connection open and shared then it also wrong.

In case of e.g. ADO.NET you have connection pooling. This means that even though you call close on connection it is not closed, it is returned to the pooler. This is a mechanism that keeps track of connections and maximizes efficiency by managing them. If you call Open to get a new connection then under the hood you may get an existing one that was used a few minutes before and that was still kept open by the pooler and returned back for reuse.

So, if the motivating force is efficiency, then it is not a path you should follow. It is already taken care of on a lower level. Refer to http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx .

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top