Singleton in C# - c#

I would like to collect more variants for create singleton class.
Could you please provide to me the best creation way in C# by your opinion.
Thanks.
public sealed class Singleton
{
Singleton _instance = null;
public Singleton Instance
{
get
{
if(_instance == null)
_instance = new Singleton();
return _instance;
}
}
// Default private constructor so only we can instanctiate
private Singleton() { }
// Default private static constructor
private static Singleton() { }
}

I have an entire article on this which you may find useful.
Oh, and try to avoid using the singleton pattern in general, due to its pain for testability etc :)

look here : http://www.yoda.arachsys.com/csharp/singleton.html
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}

Related

What can I do for a static class to be reloaded/reinstantiated?

An application I work with has a static class that loads some configuration from XML files in its constructor.
But when we make changes to one of these XML's, this class is not reloaded (as it should be, since it is static).
What can I do for this static class to be instantiated again, reloading the configuration?
Would I need to restart the IIS server? Are there some other ways?
Probably better to use a Singleton pattern with locks and with data invalidation
(typed in here so sorry in any syntax is wrong)
public class MySingleton
{
private static MySingleton _instance;
private static object _lock = new object();
private static MySingleton
{
// initialize here
}
public static MySingleton Instance
{
get
{
var singl = _instance;
if (singl != null)
return singl;
lock(_lock)
{
if (singl != null)
return singl;
_instance = new MySingleton();
return _instance;
}
}
}
public static void Invalidate()
{
lock(_lock)
{
_instance = null;
}
}
// -- your non-static methods
public bool CheckSomething(){ return true; }
}
use
// thread one
if (MySingleton.Instance.CheckSomething())
// my code
// thread two
MySingleton.Invalidate();

Is it possible to implement singleton design pattern without lock, but using volatile?

Can we use the volatile keyword, because as I understand it provides instance freshness
public sealed class Singleton
{
private static volatile Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}

What wrong with that singleton implementation

I wrote static singleton and add class inside the Singleton class.
However, it seem like it broke the pattern.
any advice why?
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public int MyProperty { get; set; } = 10;
static Singleton() { }
private Singleton() { }
public static Singleton Instance {get { return instance; } }
public class SecondSingleton
{
public Singleton secondInstance;
public SecondSingleton()
{
secondInstance = new Singleton();
secondInstance.MyProperty = 20;
}
}
}
class Program
{
static void Main(string[] args)
{
Singleton s1 = Singleton.Instance;
Singleton.SecondSingleton s2 = new Singleton.SecondSingleton();
Console.WriteLine($"s1.MyProperty = {s1.MyProperty}");
Console.WriteLine($"s2.MyProperty = {s2.secondInstance.MyProperty}");
Console.ReadLine();
}
}
Asper WIKI : Singleton restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system.
The moment you say "SecondInstance", then it is broke the pattern.
You are creating new Singleton in SecondSingleton constructor, which means secondInstance != Singleton.Instance. Instead, you should get the Instance, i.e: secondInstance = Singleton.Instance;

Singleton with Activator.CreateInstance

I have a class which implements the Singleton design pattern. However, whenever i try to get an instance of that class, using Activator.CreateInstance(MySingletonType) only the private constructor is called. Is there any way to invoke other method than the private constructor?
My class is defined as follow:
public class MySingletonClass{
private static volatile MySingletonClassinstance;
private static object syncRoot = new object();
private MySingletonClass()
{
//activator.createInstance() comes here each intantiation.
}
public static MySingletonClassInstance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new MySingletonClass();
}
}
return instance;
}
}
}
And the instantiation as follow:
Type assemblyType = Type.GetType(realType + ", " + assemblyName);
IService service = Activator.CreateInstance(assemblyType, true) as IService;
Activator.CreateInstance, except for one extreme edge-case, always creates a new instance. I suggest that you probably dont want to use Activator here.
However, if you have no choice, the hacky hack hack hack is to make a class that inherits from ContextBoundObject, and decorate it with a custom subclass of ProxyAttribute. In the custom ProxyAttribute subclass, override CreateInstance to do whatever you want. This is all kinds of evil. But it even works with new Foo().
Hei i do not know why are you creating an object of singleton class using reflection.
the basic purpose of singleton class is that it has only one object and has global access.
however you can access any of your method in singleton class like :
public class MySingletonClass {
private static volatile MySingletonClass instance;
private static object syncRoot = new object();
private MySingletonClass() { }
public static MySingletonClass MySingletonClassInstance {
get {
if (instance == null) {
lock (syncRoot) {
if (instance == null)
instance = new MySingletonClass();
}
}
return instance;
}
}
public void CallMySingleTonClassMethod() { }
}
public class program {
static void Main() {
//calling a
methodMySingletonClass.MySingletonClassInstance
.CallMySingleTonClassMethod();
}
}

Deallocate and re-instantiate new a singleton

I want to de-allocate the memory from the original singleton object and create a new one with another method.
public sealed class ObjectZ {
static readonly ObjectZ _instance = new ObjectZ();
private ObjectZ() {}
public static ObjectZ Instance{
get { return _instance; }
}
}
What would this method look like?
Singletons are usually created once and exist for the lifetime of the domain, recreating a singleton is dodgy business and by definition the code I've provided isn't truly a singleton.
The behaviour you seem to be after is a statically accessible single object cache that can be invalidated.
public static class SingletonAccessor
{
private static SomeClass _instance;
private static object _lock = new Object();
public static SomeClass Singleton
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new SomeClass();
}
return _instance;
}
}
}
public static void Recycle()
{
lock (_lock)
{
if (_instance != null)
{
// Do any cleanup, perhaps call .Dispose if it's needed
_instance = null;
}
}
}
}

Categories

Resources