Singleton design pattern is preferred to get a DB Connection
I can see nothing good coming from this class. If you want it that way (and I'm not in favor of it) you gained no benefit over a bunch of static methods. What would the singleton instance be good for? How would you put the SqlConnection variable inside a using
block?
I think a singleton is a way overused pattern for people that want global variables, but read a book that mentioned the fact globals are bad. Now they found another book stating that "Singleton" is a pattern and patterns are "good" and they finally have an excuse to have a global.
Being a global variable is a side effect of the singleton. If you are using it for the side effect, it's not a good use of the pattern. I would say it's an abuse.
Singletons are almost impossible to unit test. This one is not even thread save and does not have any use over a non-singleton. So from my point of view... delete the class.
How many people use the application is irrelevant. Each will have it's own process and it's own singleton, as bad as that may be.
Thomas
i am developer. i am working with .Net technology (v1.1 & v2.0) last 4 year. i like this forum for fast & good response and that is why i joined this forum. my friends profile id Mou :- http://stackoverflow.com/users/728750/user728750?tab=questions and Keith :- http://stackoverflow.com/users/750398/keith-costa thanks
Updated on June 05, 2022Comments
-
Thomas almost 2 years
I saw many developer create singleton class for database connection. I just like to know is it good or evil when application will be used by many users. if not good please discuss all the bad situation may occur for the above pattern.
public class ConnSingleton { private static ConnSingleton dbInstance; private readonly SqlConnection conn = new SqlConnection(@"Data Source=127.0.0.1;database=soa;User id=sa1;Password=sa1;"); private ConnSingleton() { } public static ConnSingleton getDbInstance() { if (dbInstance == null) { dbInstance = new ConnSingleton(); } return dbInstance; } public SqlConnection GetDBConnection() { try { conn.Open(); Console.WriteLine("Connected"); } catch (SqlException e) { Console.WriteLine("Not connected : "+e.ToString()); Console.ReadLine(); } finally { Console.WriteLine("End.."); // Console.WriteLine("Not connected : " + e.ToString()); Console.ReadLine(); } Console.ReadLine(); return con; } } public static void Main(string[] args) { ConnSingleton cs = ConnSingleton.getDbInstance(); cs.GetDBConnection(); Console.WriteLine("Connection established"); }
-
TyCobb about 10 yearsSingletons are also known as "Anti-Pattern".
-
Mou about 10 yearswhen we close any sql connection then then connection object immediately move to pool?
-
nvoigt about 10 years@Mou: The answer is "it depends". You should ask a new question to get a good answer.