Reputation: 2504
I am currently working on a MVC 4 project and we decided to use plain old SQL and to not rely on EntityFramework.
My question now is what is the best practice to initialize a database connection. I thought about using a Singleton that opens the connection (the connection-string is stored in the Web.config) and then use the established connection throughout the application life-cycle but I'm not sure if this is a good approach!
Upvotes: 0
Views: 3030
Reputation: 223422
For database connection, Open as late as possible and close as early as possible.
Instead of having a singleton connection, you should create connection object when ever it is necessary, and better if you use using
block, since Connection implements IDisposable
and you should get dispose the connection when you are done with it.
Upvotes: 4
Reputation: 13598
If you want to know more about a similar approach to what you've just described, look here: https://stackoverflow.com/a/10153406/1289283 . I've already answered that kind of dilemma. Be sure you won't do this on per-application scale, but rather on per-request, otherwise you get into troubles. Per-application is fine for single-user-desktop apps, NOT for webapps! And do not use singleton for this also...
Upvotes: 0
Reputation: 8116
ODP.NET
supports connection pooling so there is no reason (Unless proven otherwise in your specific case) to keep a Singleton
of your OracleConnection
object.
The best practice here is imo to use a connection (.NET connection object, not a physical connection) for each statement.
using(OracleConnection connection = ...)
{
...Do work here
}
Upvotes: 0