I'm working on an app in Asp.net.
I have a DBHandler class which handles database connections and queries,
the DBHandler constructor opens a new OleDBConnection, DBHandler's Dispose function closes and disposes of the connection, normally this works.
Some code from the DBHandler class:
readonly OleDbConnection Con;
public DBHandler()
{
string cs = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
Con = new OleDbConnection(cs);
Con.Open();
}
public void Dispose()
{
Con.Close();
Con.Dispose();
Console.WriteLine("db.dispose");
}
I also have a few request controllers/handlers which handle get and post requests,
here is some example code:
public class CountryInfoHandler : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken token)
{
HttpContent content;
HttpResponseMessage response = new HttpResponseMessage();
......
CountryInfo info = null;
using (DBHandler db = new DBHandler())
{
if (db.DoesCountryExist(parsedUri[3]))
{
info = db.Countries[parsedUri[3]];
}
else
{
info = null;
}
}
content = new StringContent(JsonConvert.SerializeObject(info));
content.Headers.ContentType.MediaType = "application/json";
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = content
};
.....
return response;
}
}
Everything works well unless multiple requests which require calls to the database come in at the same time, when that happens, I get a System.Runtime.InteropServices.SEHException.
I'm guessing this is caused by multiple database connections being open at once, is there any way to either prevent this from happening or have multiple connections without any problems?
I'm currently thinking of making it a static class with OpenConnection and CloseConnection functions that all work on a single connection but are there any better ways?