Click here to Skip to main content
15,893,161 members
Everything / Singleton

Singleton

singleton

Great Reads

by Chris875
State pattern and procedural solution illustrated
by Jon Campbell
How to utilize WCF to allow a single instance of any WPF application without needing mutexes, extra assemblies, or special "hacks".
by Scanix
SystemFramework defines interfaces, classes, and types to support a native runtime system with its own garbage collector, delegates, etc. The design of SystemFramework classes is similar to those of the .NET Framework.
by Dev Leader
About dependency injected singletons

Latest Articles

by Philippe Monteil
Core concepts and mechanisms of Microsoft.Extensions.DependencyInjection Dependency Injection
by Greg Utas
Yet another article on this topic?!
by honey the codewitch
Creating an application that can run once, but then accept command line args from subsequent runs
by honey the codewitch
This tip demonstrates how to create an app that only allows one instance to run at a time

All Articles

Sort by Score

Singleton 

5 Aug 2014 by Chris875
State pattern and procedural solution illustrated
18 May 2017 by Jon Campbell
How to utilize WCF to allow a single instance of any WPF application without needing mutexes, extra assemblies, or special "hacks".
24 Nov 2011 by Scanix
SystemFramework defines interfaces, classes, and types to support a native runtime system with its own garbage collector, delegates, etc. The design of SystemFramework classes is similar to those of the .NET Framework.
2 Aug 2013 by Dev Leader
About dependency injected singletons
21 Jul 2014 by Paul M Watt
I am not aware of a software design pattern that has been vilified more than The Singleton. Just as every other design pattern, the singleton has its merits. Given the right situation, it provides a simple a clean solution, and just as every other design pattern, it can be misused.
16 Feb 2017 by F-ES Sitecore
Using singletons it is easier to control when the class is initialised to use things like lazy-initialisation etc. Using static classes you're pretty much get what you're given, your class is initialised on creation. Also using sigleton your ultimate class is still an object rather than a...
22 Mar 2013 by OriginalGriff
Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here...A very quick search using part of your question as the search term gave : 1.6 million hits.when to use singleton pattern[^]In future, please try to do at least...
20 Jun 2013 by H.Brydon
Several thoughts:(1) your getinstance() API is not thread safe. If you have 2 or more threads calling it at the same time, you will get 2 or more objects created.(2) Is there just 1 copy of the .obj file linked somewhere? If the .cpp -> .obj file is linked into 2 or more places you...
9 Aug 2013 by Dev Leader
In this post, I’m going to focus on why singletons are “bad”, because for me it means acknowledging one of the two main perspectives–that they are the best thing since cat videos met The Internet or they are the worst thing since Justin Bieber.
16 Feb 2017 by Maciej Los
Check past answers to the questions:Singleton Class Vs Sealed Class Vs Static Class[^]How can I decide that I should use Static class or singleton class ??[^]Difference between static class and singleton pattern? - Stack Overflow[^]
25 Apr 2018 by OriginalGriff
The idea of a singleton is very simple: it's a class with a private constructor, so it cannot be instantiated form outside the class. This means that the class is absolutely in control of how many instances of the class are created, and when they are created. A singleton class creates a single...
25 Apr 2018 by CPallini
I would start form its very Wikipedia page: Singleton pattern - Wikipedia[^].
24 Feb 2012 by Sander Rossel
Actually I don't think this should be a problem. If you are using a singleton pattern you are probably calling a shared method that initializes your object. Even though the object is created on a certain thread this should not prevent it from being accessed from others (unless it's some UI...
20 Jun 2013 by JackDingler
Moved my comment here. If it fixes your issue you can mark it as the solution...When does your first call to the class occur?Perhaps it is being called before dependent libraries are loaded?Be sure that your app has fully loaded before you begin logging using any calls that aren't...
1 Aug 2013 by Dev Leader
How to structure your Singletons.
24 Apr 2014 by Henrik Jonsson
As the error message tells you textbox1 is not accessible from where you want to access it. It is neither a field or property of the containing class WordCloudHelper, nor a parameter to the method GetWordCloud. I think you have to pass in check as String parameter (assigned from...
2 Dec 2014 by Kornfeld Eliyahu Peter
Changeprivate: Single();toprivate: Single() {};
4 May 2017 by CPallini
We have even an article on this very subject: Singleton Pattern – Positive and Negative Aspects[^]. It doesn't show examples, though. You may also try to use Google for the purpose of finding code samples.
5 Oct 2011 by Paulo Zemek
All classes are naturally Lazy loaded.So a better implementation will be:public class Singletonwhere T: new(){ public static readonly T Instance = new T();}You will notice that before calling the singleton class, the object will not be loaded.Surely there are...
24 Feb 2012 by koleraba
HiI encountered a situation where I need a type of follow the singleton pattern, but the type must not be lazy loaded. This is needed becouse I want my instance to be created on the main thread - if lazy loading is used the instance will be created on the thread that first access the...
24 Feb 2012 by Shameel
Write a static method that initializes the instance and call it from the main thread before the class is first accessed.
9 May 2012 by elad2109
I have an application (Legacy code)that contains interface `Icomponent` with `save()` methodsand many classes that implement it.I want to add log after every save().I thought to use the decorator pattern to `Icomponent` with additional `log()` method.create...
9 May 2012 by Sergey Alexandrovich Kryukov
First of all, look at Apache log4net: http://logging.apache.org/log4net/[^].I think decoration components with logging is too heavy weight and too much if stiff coupling. I would allow it for an optional feature where logging is often of always useful. In general case, this is no...
9 May 2012 by Sandeep Mewara
Try: Microsoft's Enterprise Library - Logging Application Block[^]Get Logging with the Enterprise Library[^]
7 Nov 2012 by bikram990
I'm facing a problem in singleton object in c++. Here is the explanation:Problem info: I have a 4 shared libraries (say libA.so, libB.so, libC.so, libD.so) and 2 executable binary files each using one another shared library( say libE.so) which deals with files.The purpose of libE.so is...
8 Nov 2012 by Legor
It may be that your linker is configured the wrong way. Try adding -rdynamic to the linker command line.Refer to this answer which explains this behaviour:http://stackoverflow.com/questions/8623657/multiple-instances-of-singleton-across-shared-libraries-on-linux[^]
31 Jan 2013 by GigaKatowice
Hi.I need to create a GlobalConfig class. But I want to derive from it in another class.Here's an example:public class BaseConfig { public string GlobalPath {get; set;}}public class ConfigA : BaseConfig { public string pathA {get; set;}}public class ConfigB : ...
30 Jan 2013 by E.F. Nijboer
Change the private constructor to protected.Good luck!
24 Jun 2013 by zlogdan
Hi,I have been stuck at this for more than a week, as always, I suppose this is due to some of my misconceptions and the fact I am upgrading an application from VS 2003 to VS 2010.I am now upgrading a windows service developed in the past. In the previous version, running under Windows...
20 Oct 2013 by Kornfeld Eliyahu Peter
You may look into this...http://signalr.net/[^]
20 Oct 2013 by tdcmystere
Hello, thanks for response. Actually i don't use ASP.net, my client app is Winform
20 Nov 2013 by Sergey Alexandrovich Kryukov
This singleton definition makes no sense. In particular, display makes no sense, incorrect (would work, but it needs to be static, because "this" is not used) and unrelated to singleton functionality. Exposing Instance would work but means bad style.First, read this:...
20 Nov 2013 by kingsa
Hi all, I want to how create parameterised constructor in singleton class
20 Nov 2013 by SnehasishN
Hope it will help youCreate Singleton with Parameters in Constructor[^]
20 Nov 2013 by Gitanjali Singh
http://stackoverflow.com/quest...
26 Nov 2013 by dbrenth
Your constructors need... : base({arguments the base class constructor wants})after the declaration line. Without this, C# tries to initialize the base class using a constructor with no arguments and you can see from the error that there is no such constructor in the base class.Good...
26 Nov 2013 by Karthik_Mahalingam
try this code...public Singleton(String connectionString): base(connectionString) { // whatever }Make the constructor access modifiers as public and initiate base class with the connectionstring in the base class constructor..
22 Apr 2014 by Alif Marz
Hi,I have this code down. string check = textbox1.Text; if (duplicate.Contains(check) == true) { int remove = Math.Max(0, final.Count - 25); final.RemoveRange(0, remove); ...
6 May 2014 by RAHUL(10217975)
Hello Guys,I am working in windows application. We use barcode reader to login the customers. Current architect of application is in each form SerialPoet Class object is created and from DataRecieve Event data is received. Previous Developer was not able to make a singleton class SerialPort...
6 May 2014 by OriginalGriff
We can't answer that directly: you have the code and we don't!But...start by looking at the actual exception object: specifically, look at the Inner Exception - this normally contains details of the actual exception, which should help you narrow down the cause.Sorry - but at the moment,...
6 May 2014 by DJPJVS
Your static class will look someting like this public class SerialPortClass { private static SerialPortClass instance; public static SerialPortClass GetInstance() { return instance ?? new SerialPortClass(); } SerialPort...
14 May 2014 by leon de boer
The obvious issue with having multiple forms accessing a any sort of serial class or even device is working out how to deal with who is handling the data.I mean the serial object whatever it looks like holds data does the first form to ask for it get it or are the forms expected to callback...
19 Jun 2014 by V5709
I have one class (Concurrency) object in which i am initiating all db related settings .All this code is in WCF service. For instance management, i have made service instance on persession basis. Now i want to share Concurrency class object through all db layer classes. I was thinking to do...
5 Jul 2014 by George Jonsson
The singleton pattern is designed to return the same single instance of your class to all callers.To handle multiple requests at the same time you can use the lock mechanism.This MSDN page should give you some good...
5 Jul 2014 by Raul Iloc
1.If you are just want to access and store DB related settings you do not need singleton, you could use static properties that are initialized by static constructor. 2.If you want to implement more complex concurrency scenarios in the context of WCF you could find details in the next...
28 Jul 2014 by Coder93
I am new to java singleton, I want to make my class singleton, so that I have one instance of it in my code. The class which I want to be singleton is extend another class which its constructor have two entries, and entries are also singleton! Below code is, what I have done! but it is not...
28 Jul 2014 by Anton Koekemoer
Assuming that the Ui and Store classes are also implemented as Singleton, you could do it as follows.public class Singleton extends Parent{ private Ui ui; private Store store; // Static field to hold the singleton instance private static final singleton INSTANCE; //...
30 Jul 2014 by V5709
I had requirement to choose connection string at run time according to client request. so i declared an sealed class which i used to set all my db & other settings. Then i stored that particular object in cache using dictionary object & client id as key value pair. During execution i checked...
26 Sep 2014 by Sergey Alexandrovich Kryukov
Please see my comment to the question.The only reasonable answer I can give is: singleton pattern may or may not be used. This pattern should not be used often. In most cases of the application, it should not be used at all. So, what's the role of it in a Web application? No role at all, if...
25 Feb 2015 by Kr4ft3r
Hello.I am using MVC#2010 Express to create plugins for certain software. I have lots of coding experience elsewhere but remained a bit of a noob in field of Microsoft Visual Studio projects.Plugins are .dlls written in C# .NET 4.0., containing public class which implements interface...
9 Apr 2015 by JatinKhimani
I am using below control for Grid developement.http://ui-grid.info/docs/#/tutorial/101_intro[^]http://ui-grid.info/[^]I phase trouble to add another grid in this grid.i need to implement nested grid.this control have feature for grouping data but i need feature like below...
20 Oct 2015 by Manidas Payyoli
Hi iam trying an xmpp connection using singleton class,but a methode and a variable(isxmppsuccess) showing errors.My textboxes also throwing error!how i can maintain the connection in next page also?i am new to the singletonbelow mentioned is my full code and second one is error...
20 Oct 2015 by Nathan Minier
So a couple of things. Your singleton isn't thread safe, and could race with the way it's implemented now. There is an excellent article about it at:http://csharpindepth.com/Articles/General/Singleton.aspxThe easiest fix is to change the instance property to:private static...
27 Jul 2016 by Matt T Heffron
I have to provide functionality to be used by both new C# applications and a legacy C++ (VC6!!) application. So I'm planning on exposing the interfaces via in-process COM. One of the issues is that the new functionality requires carrying some state across uses of these COM interfaces although...
14 Jul 2016 by KarstenK
I know that some global named pipes are available, which enable you to transfer data. At one side you must properly manage your server while at the other side your clients are in charge.It is a combination of named pipes and Inter-Process Communication. Use the "global" prefix.I also can...
27 Jul 2016 by Matt T Heffron
I finally ended up with pretty much my second "option" above:I was able to restructure the code so the singleton class wasn't necessary.Instead, the functionality requiring the persistence was able to be moved into the classes doing the actual work and exposed there as static...
8 Nov 2016 by Giridharan_BE
I want to create a web application using SignalR. Upon creation, I want to validate the pages with the custom authentication using UserName and Password. When the user opens the page which is created using SignalR to fetch realtime data, an instance of the page will be created.When the user...
8 Nov 2016 by vaibhav43
public sealed class Singleton{ private static Singleton instance = null; private static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { lock (padlock) { ...
7 Jan 2017 by Wendelius
You could use a singleton pattern to ensure that only one instance exists, but I think that it would be easier just to loop through Application.OpenForms Property (System.Windows.Forms)[^]. Loop through the collection, check if the form exists and if it does, activate it, if it doesn't,...
7 Jan 2017 by Maciej Los
I'd suggest to read past answers[^].
16 Feb 2017 by Dinesh Kumar Dora
When we can do the same thing using static classes, why do we need singleton?I researched a lot but couldn't understand the basic difference. Can somebody explain me in simple words with examples.ThanksDineshWhat I have tried:google searched but couldnt understand from the...
14 Sep 2017 by Member 13409686
is it completely thread safe in C++ 98 if not, how we can achieve thread safe singleton in C++98 ? MySingleton * GetInstance() { if (m_pOnlyOneInstance == NULL) { EnterCriticalSection(); if (m_pOnlyOneInstance == NULL) // Solution 1 and 2 gaps...
31 May 2021 by vaibhav1800
This is an Example of a Singleton class with Eager Loading Pattern and a multithreaded environment is created by using Parallel.Invoke func. (Console App) The Question is : Why only object is being created here ? Kind of confused. Try this code...
31 May 2021 by OriginalGriff
Quote: The Question is : Why only object is being created here ? Because that is what the Singleton pattern is all about: a single instance is created and no others can be. Singleton pattern - Wikipedia[^]
28 Jun 2021 by Greg Utas
It's difficult to answer given the brevity of your question. I wouldn't call a session a design pattern. It could be called a protocol pattern, but it's not a software pattern in the usual sense of the term. As a protocol pattern, it consists of...
9 Aug 2022 by Philippe Monteil
Core concepts and mechanisms of Microsoft.Extensions.DependencyInjection Dependency Injection
24 Sep 2015 by Anton Angelov
Explains in detail how to implement Singleton Design Pattern. Practical examples how to use it in automation tests, following all SOLID principles.
14 Jul 2015 by Shivprasad koirala
In this article we will learn C# Design pattern and Architecture pattern Step by Step with a project.
13 Dec 2013 by comiscience
This is a singleton template class which can be used by classes with a private constructor.
5 Apr 2013 by Boris Brock
This article presents a reusable base class for implementing singletons in C#.
14 Sep 2017 by Andrew Kirillov
Hello, Check the "C++ and the Perils of Double-Checked Locking"[^] article by Scott Meyers and Andrei Alexandrescu to find why the sample code you've got fails. The article does provide a sample of thread-safe singleton. Yes, it does suffer from performance issue you are trying to solve with...
25 Nov 2020 by Greg Utas
Yet another article on this topic?!
24 Apr 2017 by Habibur Rony
This topic will cover the bad design practice using STUPID and good design practice using SOLID. Detailed explanation for Single Single Responsibility Principle, Open and Closed Principle, Liskov Substitution Principle, Interface Segregation Principle and Dependency Inversion (DI) Principle.
27 Apr 2015 by HiDensity
Localization of an application at runtime - "On the fly"
20 Oct 2013 by tdcmystere
Hello, First of all sorry for my english. My Case: I have an application to query Active directory and some log files and show the output in a nice GUI. This app help many of my colleges to get information about users. I would like to be able to notify my stuff about one of...
27 Feb 2012 by StevenLJackson1
Describes the .NET ReaderWriterLock object and how to use it effectively to create a thread safe Singleton.
21 Nov 2013 by kingsa
Hi All , I was tried to work with wcf service using singleton pattern getting error 'System.Data.Linq.DataContext' does not contain a constructor that takes 0 argumentscan u guide how to solve this error , using System;using System.Data;using...
1 May 2020 by honey the codewitch
Creating an application that can run once, but then accept command line args from subsequent runs
22 Mar 2013 by Akhil Mittal
Can any one give me the best example of when to use singleton pattern.Don't discuss how to use , only discuss when and why to use??
30 Jul 2012 by PratapReddyP
Singleton Pattern : This is a pattern which is widely used when there is a situation to create only one instance of a class.Lets demonstrate the pattern using a simple example. Earlier i used to wonder how load balancer servers work.
8 Jan 2018 by Akhil Mittal
This article covers Singleton Pattern in the most simplistic and easy to understand. The article will also talk about Static classes and the differences between singleton design pattern and static classes.
9 Jan 2018 by Akhil Mittal
In this article, we’ll discuss Lazy initialization, the lazy keyword, why you make singleton class a sealed class and what are the differences between singleton and static class.
17 Oct 2011 by omid rezaei hanjani
Customized implementation of the Singleton pattern using Generics.
1 May 2020 by honey the codewitch
This tip demonstrates how to create an app that only allows one instance to run at a time
11 Oct 2013 by ASP.NET Community
Singleton The Singleton Design Pattern ensures that only a single instance of a given object can exist.It does this by making the class
2 Dec 2014 by Member 11279587
class Single{private: Single();public: static Single& Single::Instance() { static Single the_instance; return the_instance; }};int main(){ cout
20 Nov 2013 by Jobless Creature
Just try Singleton.display("input string").. For singleton, you can consume as classname.methodname()..does this help?
26 Oct 2011 by rj45
simple Asp.net singleton
7 Jan 2017 by Member 10850253
I have a C# windows Form application that creates multiple instances of the same window, when I double click the shortcut, but I only want one single instance of the window.Can someone please tell me how to accomplish this?Thanks.What I have tried:I tried what was described in this...
7 Jan 2017 by Member 10850253
I did this in program.cspublic static bool bf = false; static void Main() { foreach (Form form in Application.OpenForms) { if (form.Name == "BatteryMonitorForm") { bf = true; ...
25 Apr 2018 by Prashanth Shridharchar
Hi all, i'm new to Singleton design pattern, if can ANYONE EXPLAINS or quick understanding of what is Singleton design pattern and how should i use for simple web application or anything. What I have tried: Tried with ONLINE EXAMPLE but did not understood
28 Jun 2021 by Ishmeet Kaur
I Have got two answers for the internet Singleton and Factory design pattern? Which should we use? Both of them? and Why? What I have tried: I Have got two answers for the internet Singleton and Factory design pattern?
20 Nov 2013 by kingsa
Hi All, I am new to singleton class how to call the display method can u guide or send snippets public sealed class Singleton{ private static readonly Lazy lazy = new Lazy(() => new Singleton()); public static Singleton Instance { get...
14 May 2014 by Mohammad Reza Valadkhani
if i were you i would write windows Service for handling serial port and then use some key points for communication between windows form and windows service application.but for your case it`s better to write up your code then guys can help you.
25 May 2014 by RAHUL(10217975)
I made SerialPort reader into a separate static class. Then I created a datareceive event in that class and fire it every time data is received. And that event I subscribe in each form and now when I scan the card datarecived event is firing in every form.
26 Sep 2014 by vinay digil
whats the role of singleton pattern in web application?10 requests from different users for log in how it will be used?instance will 10=1 or 10=10?if 10=1? how it will be handled?if 10=10? how it will be? where the instance is get stored? in case of web.
2 Mar 2017 by Vijai Anand.G
Hope this will help you.Using Singleton Pattern you can Ensure only one Instance of Object is Created.It can be used as Global Access point.For Example Scenario, we can use Singleton Pattern for...
4 May 2017 by maverick1991
Hi All, I have been reading singleton pattern,it's advantages and disadvantages. Since I am new to this I am not able to understand the detailed nature of disadvantages. Can someone please explain in detail the disadvantages of singleton with any example if possible. eg: 1. How do they deviate...