I have BasePage.cs class which is being used by other .cs files instead of System.Web.UI.Page (public partial class page : BasePage).
I am using it for opening and closing SQL connections to make sure every SQL connection gets closed.
Code looks like this
{
public class BasePage: System.Web.UI.Page
{
public SqlConnection globalConnection;
protected override void OnInit(EventArgs e)
{
globalConnection = new SqlConnection();
globalConnection.ConnectionString = ConfigurationManager.ConnectionStrings["kontemiConnectionString"].ToString();
globalConnection.Open();
}
protected override void OnUnload(EventArgs e)
{
if (globalConnection != null)
{
globalConnection.Close();
}
}
}
}
So far it has worked really well for me. It means that every time a connection opens it also gets closed. Or at least I thought so.
My question is whether this solutions is bulletproof and every single connection gets closed in case there is some processing error during code execution. When tracing this code, if I on purpose create error 500 it always goes to OnUnload event and gets closed.
So, do you think is this execution safe?
(To stop discussion whether I shouldn’t open SQL when I actually need it, answer is that every page which uses BasePage also opens a SQL connection.)
I might be wrong, but my guess would be that the connection does not get closed if the page lifecycle is ended through an exception before
OnUnloadfires. The very least you could do to prevent this is make sure you catch all exceptions on a global ‘last-chance’ level, and close the connection there. I still think using connections locally, ideally withusingblocks, is the better solution, because it doesn’t keep connections open longer than it needs to, and you don’t have to worry about closing them (the semantics ofusingwill do the work for you).