I have an asp.net web site and a database.
The web site has a web service for storing feedback from my software.
As far as I know, IIS will reuse the created object for sequential requests.
This gives a reason to connect to the DB in web service’s constructor, properly implement Dispose() method, and use the connection for serving each [WebMethod] Request(). Current edition follows this patters.
On the other hand I’m afraid that the timespan between sequential requests to webservice will be larger that DB connection timeout. I therefore will need to catch some exception and recreate connection (right?)
The alternative approach is to connect and close in each [WebMethod] Foo(). But I’m afraid this may hurt the performance.
To sum up,
should I connect to DB in constructor and close connectiion in Dispose() or connect and close DB for each request?
You should connect for each request.
The page instance is only used for a single request, so you can’t store a connection in it to reuse it. You would have to store it somewhere else, and that is so complicated (with thread safety and such) that it’s definitely not worth it.
When you close the connection, the actual database connection is returned to the connection pool. The connection pool takes care of resetting the connection properly when it’s reused for the next connection object that you create, so that you get a connection that is alive and untainted by previous usage.
The connection pool works fine, and you should use it instead of trying to create one yourself.
You don’t have to do anything special to use the connection pooling, it’s built into the database driver. Just open and close connection objects as usual.