How to recreate singleton instance in c# - c#

I have a singleton class, it is reading config file.
public sealed class SettingsHelper
{
private static readonly SettingsHelper _Instance = new SettingsHelper();
static SettingsHelper()
{
}
public static SettingsHelper Instance
{
get
{
return _Instance;
}
}
private NameValueCollection _SettingsSection = null;
public SettingsHelper()
{
_SettingsSection = new NameValueCollection(ConfigurationManager.AppSettings);
}
.....
}
}
But if config file getting changed the singleton do not picking up the change.
Is there any way to recreate the instance of singleton(call its constructor) or i should create separate method which will be reinitiating the instance of singleton?

You're trying to throw away the very first purpose of singleton pattern. A singleton is there, just to prevent any other code from instantiating a new instance of that class. To make a singleton class, you should not have public constructors at all. You already have a public constructor.
I encourage you to read the first line, just the first line of this Wikipedia article about Singleton Pattern.
What you're trying to do, is called cache dependency in C#. You're trying to cache Web.config's app settings and you are dependent on Web.config's change. You should search that.

Recreating a singleton is abad idea - references to the 'old' singleton will stay.
So it's no longer a singelton!
In your case I would create new settings. Why not make a public method LoadSettings() and call that?
public sealed class SettingsHelper
{
private static readonly SettingsHelper _Instance = new SettingsHelper();
private NameValueCollection _SettingsSection = null;
// ...
private SettingsHelper()
{
LoadSettings()
}
public void LoadSettings()
{
_SettingsSection = new NameValueCollection(ConfigurationManager.AppSettings);
}
.....
}
}
BTW: make SettingsHelper() private...

It will be better to create a separate method inside your singleton class to read the settings again. Obviously, with this approach, you will have to call this method from your code.

Related

Singleton without sealed class and thread safety issues

I was asked to write Singleton in the interview today. I wrote the below, please note, I used "property set" method to set and then I returned the instance using "get" method. But I see in internet that most places they use only get, meaning, what I did below is wrong? Sorry I dont have VS ide with me to verify it now, so posting it here.
Also, some used sealed class including with private constructor. Why sealed with private cons?
public class Singleton
{
private static readonly Singleton instance;
private Singleton() {}
public static Singleton Instance
{
set
{
if(instance == null){
instance = new Singleton();
}
}
get
{
return instance;
}
}
}
My advice is to try to compile and run the code yourself. It's by far the easiest way to understand how it works.
If you would try to build your code you would get the following error :
Error CS0198 A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
In other words, you should instantiate your instance inside the constructor.
Regarding your question, a private constructor is needed to prevent access from outside your class and also it is enough to make sure that other classes cannot inherit from your class. You don't really need the sealed.
You can find a really good summary regarding the singleton pattern # https://csharpindepth.com/articles/singleton
#Learner Since its a interview question and mostly in India they ask to write to Psuedo code to evaluate the candidate coding skills, I try to fit myself in the candidate shoes to give the answer.
Well design patterns has evolved over a period of time with advancements in the programming language and Singleton is not a exception. There are many ways that we can create a Singleton class using C#. I would like to showcase few of the flavors that I can able to recollect
1. Plain vanilla Singleton without Thread-Safety
public sealed class Singleton
{
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
2. Singleton with Thread Saftey
public sealed class Singleton_ThreadLock
{
Singleton_ThreadLock()
{
}
private static readonly object padlock = new object();
private static Singleton_ThreadLock instance = null;
public static Singleton_ThreadLock Instance
{
get
{
// Uses the lock to avoid another resource to create the instance in parallel
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_ThreadLock();
}
return instance;
}
}
}
}
3. Singleton - Double Thread Safe
public sealed class Singleton_DoubleThreadSafe
{
Singleton_DoubleThreadSafe()
{
}
private static readonly object padlock = new object();
private static Singleton_DoubleThreadSafe instance = null;
public static Singleton_DoubleThreadSafe Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_DoubleThreadSafe();
}
}
}
return instance;
}
}
}
4. Singleton - Early Initialization
public sealed class Singleton_EarlyInitialization
{
private static readonly Singleton_EarlyInitialization instance = new Singleton_EarlyInitialization();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton_EarlyInitialization()
{
}
private Singleton_EarlyInitialization()
{
}
public static Singleton_EarlyInitialization Instance
{
get
{
return instance;
}
}
}
5. Singleton - Lazy Initialization using .Net 4.0+ Framework
public sealed class Singleton
{
private Singleton()
{
}
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return lazy.Value;
}
}
}
Caveats:
Well there are few people who create instance of the class using reflection (I did in one of my framework) but his can also be avoided. There are few samples in net that can show how to avoid it
Its always best practice to make the Singleton class as sealed as it will restrict developers from inheriting the class.
There are lots of IOC's in the market that can create Singleton instance of a normal class without following the above Singleton implementation.

c# Singleton Pattern vs Static Property

When I tried to use 2 different versions of the same class , they act actually the same.
I searched but can't find a satisfied answer for this question
What are the differences between Singleton and static property below 2 example, it is about initialization time ? and how can i observe differences ?
Edit : I don't ask about differences static class and singleton. Both of them non static, only difference is, first one initialized in Instance property, second one initialized directly
public sealed class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
public sealed class Singleton2
{
private static Singleton2 instance = new Singleton2();
private Singleton2()
{
}
public static Singleton2 Instance
{
get
{
return instance;
}
}
}
Your first singleton implementation isn't thread safe; if multiple threads try to create a singleton at the same time it's possible for two instances to end up being created. Your second implementation doesn't have that flaw.
Other than that, they're functionally the same.
The instance of the Singleton class will be created the first time it is requested by the Singleton.Instance method.
The instance of Singleton2 will be created on initialization of its type which can be caused by several mechanisms. It will certainly be created before accessing any property or method on the Singleton2 class

Multiple events get different instances of a field declared in singleton?

Edit: My bad, no strage events behavior. Error was somewhere else in code. Thx everybody for help. Please ignore this question
Please can someone explain to me what is happening here. I'm experiencing an unexpected event behaviour.
There is a singleton class:
internal class QueueListener
{
private static readonly object QueueChangeLock = new object();
private readonly List<IQueuedJobExecutioner> jobsQueue = new List<IQueuedJobExecutioner>();
// Here comes singleton private constructor, Instance property, all classic.
// Important line in constructor is this:
QueueManager.NewJobQueued += NewJobQueuedHandler;
private void NewJobQueuedHandler(object sender, NewJobQueuedEventArgs args)
{
lock (QueueChangeLock)
{
// This is the problematic place, note this!
jobsQueue.Add(args.QueuedJobExecutioner);
}
}
}
Now there is a second class:
public class QueueManager
{
public static event NewJobQueuedEventHandler NewJobQueued;
protected void RaiseNewJobQueuedEvent(IQueuedJobExecutioner queuedJobExecutioner)
{
if (NewJobQueued != null)
{
NewJobQueued(this, new NewJobQueuedEventArgs { QueuedJobExecutioner = queuedJobExecutioner });
}
}
}
Both classes reside on a server. Via WCF calls client executes sth like new QueueManager().MyMethod(), which calls RaiseNewJobQueuedEvent.
Everything works fine, however if two events are raised almost at the same time, I see in debugger the following at the problematic place (see comment in QueueListener):
First event comes. jobsQueue has no members.
jobsQueue.Add() is executed. jobsQueue has 1 member.
Second event comes. jobsQueue has no members! How? It's in a singleton and we just added a member!
jobsQueue.Add() is executed. jobsQueue has 1 member. Again. Member added in step 2 has been lost.
Not judging the design itself (it has some "historical" reasons), why exactly is this happening? Is this expected behavior and event somehow gets at some point a snapshot of jobsQueue or this is nonesense and I'm just missing some part of the puzzle?
Edit:
I'd say it is a singleton, and is implemented like this (these lines were omitted in original post):
class QueueListener
{
private static readonly object SyncRoot = new object();
private QueueListener()
{
//...
}
public static QueueListener Instance
{
get
{
if (instance == null)
{
lock (SyncRoot)
{
if (instance == null)
{
instance = new QueueListener();
}
}
}
return instance;
}
}
}
Yuval is correct, your class is not a singleton. A singleton is created when you have a public static method to create an instance and a private constructor. The private constructor ensures that the only way to create an instance is through the public method.
Please see https://msdn.microsoft.com/en-us/library/ff650316.aspx for more details.
Your QueueListener class is not actually a singleton. What that means for you is that you are creating multiple instances of it. To fix that you have to add the static keyword in the class declaration and declare a static constructor as well. Try changing your class to what is shown below:
internal static class QueueListener
{
private static readonly object QueueChangeLock = new object();
private static readonly List<IQueuedJobExecutioner> jobsQueue = new List<IQueuedJobExecutioner>();
// This is the singleton constructor that will be called
static QueueListener()
{
// Here comes singleton private constructor, Instance property, all classic.
// Important line in constructor is this:
QueueManager.NewJobQueued += NewJobQueuedHandler;
}
// Rest of class code...
}

Static constructor in Singleton design pattern

On MSDN I found two approaches to creating a singleton class:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton Instance {
get {
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
and
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance {
get { return instance; }
}
}
My question is: can we just use a static constructor that will make for us this object before first use?
Can you use the static constructor, sure. I don't know why you'd want to use it over just using the second example you've shown, but you certainly could. It would be functionally identical to your second example, but just requiring more typing to get there.
Note that your first example cannot be safely used if the property is accessed from multiple threads, while the second is safe. Your first example would need to use a lock or other synchronization mechanism to prevent the possibility of multiple instances being created.

How to implement a singleton in C#?

How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue )
{
}
}
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
Singletons only make sense if both of these conditions are true:
The object must be global
There must only ever exist a single instance of the object
Note that #2 does not mean that you'd like the object to only have a single instance - if thats the case, simply instantiate it only once - it means that there must (as in, it's dangerous for this not to be true) only ever be a single instance.
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).
If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
Thats my opinion anyway.
Singleton != Global. You seem to be looking for the keyword static.
You can really simplify a singleton implementation, this is what I use:
internal FooService() { }
static FooService() { }
private static readonly FooService _instance = new FooService();
public static FooService Instance
{
get { return _instance; }
}
Hmm, this all seems a bit complex.
Why do you need a dependency injection framework to get a singleton? Using an IOC container is fine for some enterprise app (as long as it's not overused, of course), but, ah, the fella just wants to know about implementing the pattern.
Why not always eagerly instantiate, then provide a method that returns the static, most of the code written above then goes away. Follow the old C2 adage - DoTheSimplestThingThatCouldPossiblyWork...
I would recommend you read the article Exploring the Singleton Design Pattern available on MSDN. It details the features of the framework which make the pattern simple to implement.
As an aside, I'd check out the related reading on SO regarding Singletons.
Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:
/// <summary>
/// Thread-safe singleton implementation
/// </summary>
public sealed class MySingleton {
private static volatile MySingleton instance = null;
private static object syncRoot = new object();
/// <summary>
/// The instance of the singleton
/// safe for multithreading
/// </summary>
public static MySingleton Instance {
get {
// only create a new instance if one doesn't already exist.
if (instance == null) {
// use this lock to ensure that only one thread can access
// this block of code at once.
lock (syncRoot) {
if (instance == null) {
instance = new MySingleton();
}
}
}
// return instance where it was just created or already existed.
return instance;
}
}
/// <summary>
/// This constructor must be kept private
/// only access the singleton through the static Instance property
/// </summary>
private MySingleton() {
}
}
Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/ or http://code.google.com/p/autofac/.
To register / consume a type configured as a singleton in autofac you would do something like the following:
var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))
var container = builder.Build();
var configured = container.Resolve<RequiresDependency>();
The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.
public class Globals
{
private string setting1;
private string setting2;
#region Singleton Pattern Implementation
private class SingletonCreator
{
internal static readonly Globals uniqueInstance = new Globals();
static SingletonCreator()
{
}
}
/// <summary>Private Constructor for Singleton Pattern Implementaion</summary>
/// <remarks>can be used for initializing member variables</remarks>
private Globals()
{
}
/// <summary>Returns a reference to the unique instance of Globals class</summary>
/// <remarks>used for getting a reference of Globals class</remarks>
public static Globals GetInstance
{
get { return SingletonCreator.uniqueInstance; }
}
#endregion
public string Setting1
{
get { return this.setting1; }
set { this.setting1 = value; }
}
public string Setting2
{
get { return this.setting2; }
set { this.setting2 = value; }
}
public static int Constant1
{
get { reutrn 100; }
}
public static int Constat2
{
get { return 200; }
}
public static DateTime SqlMinDate
{
get { return new DateTime(1900, 1, 1, 0, 0, 0); }
}
}
I like this pattern, although it doesn't prevent someone from creating a non-singleton instance. It can sometimes can be better to educate the developers in your team on using the right methodology vs. going to heroic lengths to prevent some knucklehead from using your code the wrong way...
public class GenericSingleton<T> where T : new()
{
private static T ms_StaticInstance = new T();
public T Build()
{
return ms_StaticInstance;
}
}
...
GenericSingleton<SimpleType> builder1 = new GenericSingleton<SimpleType>();
SimpleType simple = builder1.Build();
This will give you a single instance (instantiated the right way) and will effectively be lazy, because the static constructor doesn't get called until Build() is called.
What you are describing is merely static functions and constants, not a singleton. The singleton design pattern (which is very rarely needed) describes a class that is instantiated, but only once, automatically, when first used.
It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.
Static constants and functions are just that: code that doesn't need an instance at all.
Ask yourself this: "Will this class break if there is more than one instance of it?" If the answer is no, you don't need a singleton.
hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.
If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.
My 2 cent
Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.
You can make a simple manual static singleton implementation for your common (non-static) class by adding a static property Instance (name can vary) into it with initialization like this:
public class MyClass
{
private static MyClass _instance;
public static MyClass Instance => _instance ?? (_instance = new MyClass());
// add here whatever constructor and other logic you like or need.
}
Then it can be resolved anywhere from this namespace like this:
var myClass = MyClass.Instance; // without any new keyword
myClass.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticProperty = "new value";
By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance
public class MySingleton
{
private static MySingleton sngltn;
private static object locker;
private MySingleton() {} // Hides parameterless ctor, inhibits use of new()
public static MySingleton GetMySingleton()
{
lock(locker)
return sngltn?? new MySingleton();
}
}
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TEClaim.Models
{
public class LogedinUserDetails
{
public string UserID { get; set; }
public string UserRole { get; set; }
public string UserSupervisor { get; set; }
public LogedinUserDetails()
{
}
public static LogedinUserDetails Singleton()
{
LogedinUserDetails oSingleton;
if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
{
oSingleton = new LogedinUserDetails();
System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
}
else
{
oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
}
//Return the single instance of this class that was stored in the session
return oSingleton;
}
}
}
Now you can set variable value for the above code in your application like this..
[HttpPost]
public ActionResult Login(FormCollection collection)
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
User_Details.UserID = "12";
User_Details.UserRole = "SuperAdmin";
User_Details.UserSupervisor = "815978";
return RedirectToAction("Dashboard", "Home");
}
And you can retrieve those value like this..
public ActionResult Dashboard()
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
ViewData["UserID"] = User_Details.UserID;
ViewData["UserRole"] = User_Details.UserRole;
ViewData["UserSupervisor"] = User_Details.UserSupervisor;
return View();
}
In c# it could be (Thread safe as well as lazy initialization):
public sealed class MySingleton
{
static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
public static MySingleton Instance => _instance.Value;
private MySingleton() { }
}

Categories