HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Singleton implementation of a database connection

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
databaseimplementationsingletonconnection

Problem

I have implemented as follows, a class applying singleton pattern to get a global single access to database.
I intend to provide a thread-safe implementation.

using System.Data.SqlClient;

public sealed class Database
    {
        private static volatile SqlConnection instance;
        private static object syncRoot = new object();
        private const string connectionString = "Data Source=ServerName;" +
                                                "Initial Catalog=DataBaseName;" +
                                                "User id=UserName;" +
                                                "Password=Secret;";

        private Database() { }

        public static SqlConnection Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new SqlConnection(connectionString);
                    }
                }

                return instance;
            }
        }
    }

Solution

As per the docs

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.90).aspx


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

This means that while the Singleton instance can be technically correct, it is not correct in this specific context of the SqlConnection class if you plan to access instance members from different threads (and you possibly do).

Context

StackExchange Code Review Q#159351, answer score: 4

Revisions (0)

No revisions yet.