ASP .NET Application_Start Event + Connection to a DB

1.1k views Asked by At

I have started developing a full-web application by using the ASP .NET MVC 3 framework. I am a MVC 3 beginner developer.

On the server-side I am going to execute some queries to a DB. Consequently I will have to make a connection to the DB.

I would like to know if it is better to make a connection in the beginning of each action method or in an event handler. I have thought about making the connection in the Application_Start event handler and then storing an object representing my connection into the application state. Does this way present disadvantages ?

Thanks in advance for your future answer

1

There are 1 answers

0
Mitch Wheat On BEST ANSWER

Open and close the connection as required (rather than keeping one open). Let connection pooling work for you.

10 Tips for Writing High-Performance Web Applications (ASP.NET but contains relevant advice):

Tip 3—Connection Pooling

Setting up the TCP connection between your Web application and SQL Serverâ„¢ can be an expensive operation. Developers at Microsoft have been able to take advantage of connection pooling for some time now, allowing them to reuse connections to the database. Rather than setting up a new TCP connection on each request, a new connection is set up only when one is not available in the connection pool. When the connection is closed, it is returned to the pool where it remains connected to the database, as opposed to completely tearing down that TCP connection.