I’m not using LINQ-to-SQL or Entity Framework bits in a web app, and have currently been using something like this (this is for a class project):
using System.Data;
using System.Data.SqlClient;
namespace StackOverflowClone.Models
{
public class Database
{
public static SqlConnection ActiveConnection { get; private set; }
static Database()
{
ActiveConnection = new SqlConnection(
"Data Source=********.database.windows.net;" +
"Initial Catalog=EECS341;Uid=*****;Pwd=*******;" +
"MultipleActiveResultSets=True;");
ActiveConnection.Open();
}
}
}
However this seems to cause threading issues because the static initializer runs once per server process, rather than once per request.
Does the framework provide a built in method of handling this or should I just have a function that coughs up database connections new’d up each time?
Yes, do this. Let ADO.NET connection pooling handle the details for you. Your goal should be to keep the connection open for as short a period of time as possible.
So, create a static
GetConnection()method that returns a new open connection. Use this within ausingstatement so it can be closed and returned to the connection pool as soon as possible.