We are writing an ASP.NET application. We have used singleton for
instantiating a database connection as explained in the following code
sample.

Design thought was to use only one instance of MyDb across all the pages
in this web application. Is this a correct singleton implementation for
Asp.NET web application for managing database connection?

//Code Reference

public sealed class AppDbProvider : IDisposable
    {
        public static readonly AppDbProvider instance = new AppDbProvider
();

        private readonly MyDb _d = new MyDb
(ConfigurationManager.ConnectionStrings["my_connection"].ConnectionString,
                               ConfigurationManager.ConnectionStrings
["my_connection"].ProviderName);

        public MyDb GetDbConnection()
        {
            if (_d != null)
                return _d;
            else
                throw new Exception("Problem with Database Connection in
AppDbProvider.");
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_d != null)
                _d.Dispose();

                Dispose();

        }

        #endregion
    }

Now in the code behind file, we have following code


public partial class CreatePage
    {
private AmgDb _d;

try
{
     _d = AppDbProvider.instance.GetDbConnection();
}
Catch (Exception exce)
{
  Response.write(exce.message);
}

     }

And in the end in page unload event, we have following cleanup code

protected void Page_Unload(object sender, EventArgs e)
        {
            if (_d != null)
            {
                _d = null;
            }
        }

Thanks.

Abhi

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to