Creating thread-safe singleton wrapper for DI container - c#

I Created a wrapper for Ninject DI container which I intend to use in WPF application. I would like it to be thread safe in case I need to open new windows in separated threads, but I am confused about using volatile keyword and locking. As much as I'm aware of, locking is pretty much Straightforward to understand but I'm not shore about using volatile keyword. From my googling results I came to understanding that volatile keyword ensures safe read access for specified instance in multithreaded environment but doesn't provide any kind of safety when making changes in memory space occupied by the specified instance. I combined my solution with some examples of thread-safe singleton patterns and came up with this wrapper that would serve me as a service locator:
public class NinjectResolver
{
private static object syncRoot = new object();
private static volatile NinjectResolver instance = null;
private static volatile IKernel kernel = null;
public static NinjectResolver GetInstance()
{
lock (syncRoot)
{
if (instance == null)
instance = new NinjectResolver();
}
return instance;
}
static NinjectResolver()
{
lock (syncRoot)
{
if (kernel == null)
kernel = new StandardKernel();
}
}
public void AddBindings(Dictionary<Type, Type> bindings)
{
lock (syncRoot)
{
foreach (var binding in bindings)
{
Type IType = binding.Key;
Type ImplementationType = binding.Value;
kernel.Bind(IType).To(ImplementationType);
}
}
}
private NinjectResolver()
{
}
/// <summary>
/// Resolves All dependencies for requested instance and returns that instance
/// </summary>
/// <typeparam name="T">Requested Implementation type</typeparam>
/// <returns>Instance of Implementation type</returns>
public T Resolve<T>()
{
return kernel.TryGet<T>();
}
/// <summary>
/// Resolves property injection dependencies in already instantiated Implementation types
/// </summary>
/// <param name="obj">Specified instance of implementation type</param>
public void Inject(object obj)
{
kernel.Inject(obj);
}
}
My question is this: Do I need to use locking in specified places since initialization will take place inside App.xaml.cs (first call of GetInstance() ) and do these static fields need to be declared as volatile or I can omit that part since they are more or less readonly in this construction. I would appreciate if someone could shred some light on this.

To implement a thread-safe singleton pattern you have two options basically:
1.Double-checked locking
public static NinjectResolver GetInstance()
{
if(instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new NinjectResolver();
}
}
return instance;
}
2.Initialize the instance upon declaration
private static volatile NinjectResolver instance = new NinjectResolver();
public static NinjectResolver GetInstance()
{
return instance;
}
Also you can drop the code inside the static block and just use:
private static volatile IKernel kernel = new StandardKernel();

Related

Mixing Dependency Injection with the Singleton Design Pattern

I have a Singleton in my Project looking like this:
//Create a Singleton
static MySingleton Instance;
private static readonly object Padlock = new object();
/// <summary>
/// Singelton Method, to make sure only one instance of this class exists at runtime.
/// </summary>
/// <returns></returns>
public static MySingleton GetInstance()
{
//Thread Safety
lock (Padlock)
{
if (Instance == null)
{
Instance = new MySingleton();
}
return Instance;
}
}
private MySingleton()
{
}
//[...]
The Singleton contains several other classes as Properties, which should never be null.
Normally I'd use DependencyInjection to gurantee each new object gets all necessary parameters on instantiation.
Like this:
IHelperClass Helper {get; set;}
IExectiveClass Executive {get; set;}
public NotMySingleton(IHelperclass helper, IExecutiveClass executive)
{
Helper = helper;
Executive = executive;
}
But I have no idea how to combine DependencyInjection with a Singleton Pattern.
Is there a way to use Singletons with DependenyInjection? What is common practice? What alternatives do I have (if this is not a suitable option)?
All DI frameworks provide a way to define the lifetime of objects instantiated by the DI container.
One lifetime scope is usually Singleton.
If you let the DI framework control the lifetime of your MySingleton, DI will just work.
One remark though, any class which gets injected into the singleton will also be a singleton, no matter how the scope of those dependencies was defined.
If you cannot use or don't want to use the DI framework to create your MySingleton instance, one way to achieve the same would be to make the DI container available and resolve whatever the instance needs from the DI container, manually.
Some might consider this an antipattern though.
Using a DI framework that provides a DI container would be the way to go, however for cases where this is not possible, perhaps one can use the GetInstance() method to inject the dependencies.
Something like this.
//Create a Singleton
static MySingleton Instance;
private static readonly object Padlock = new object();
//The method that would be used by production code to use the class.
public static MySingleton GetInstance()
{
if (Instance != null)
{
return Instance;
}
IDependentService srv = new ConcreteService();
return GetInstance(srv);
}
//The method that allows for injecting dependencies for unit testing.
public static MySingleton GetInstance(IDependentService service)
{
if (Instance == null)
{
lock (Padlock)
{
if (Instance == null)
{
Instance = new MySingleton(service);
}
}
return Instance;
}
private MySingleton(IDependentService service)
{
//...
}

Problem with an object pooling mechanism, Queue containing the pool can't be static because static variables aren't inherited

I'm setting up an object pooling mechanism in unity, basically how it works is:
You have a base abstract class called "Poolable", with a static queue containing objects in it (In this case GameObjects), there's a class called Projectile which inherits from Poolable as that's what i currently want to be pooled. It further extends to a Bullet class which inherits from Projectile, but the problem is, if i had an Arrow class which inherits from Projectile, it would use the same pool because the pool is static inside Poolable. Does anyone know a way i could tackle this issue?
I thought about making it non-static, but then the objects wouldn't know about the pool, they'd know about their own pool. Same with interfaces but they don't accept variables which aren't properties
The only current fix i see is adding it to each script that i use a pool on, but that then defeats the whole purpose of inheritance as i was trying to make a polymorphic-like structure where you'd have multiple poolables, multiple projectiles, maybe multiple bullets/arrows?
public abstract class Poolable : MonoBehaviour
{
protected static Queue<GameObject> objPool = new Queue<GameObject>(); // doesn't work because every poolable object will use this pool only
[SerializeField] protected GameObject prefab;
public GameObject Get()
{
if(objPool.Count == 0)
{
AddObjects();
}
return objPool.Dequeue();
}
protected void ReturnToPool(GameObject retObj)
{
objPool.Enqueue(retObj);
retObj.SetActive(false);
}
AddObjects()
{
}
}
If I am not mistaken, you need your object pool to be homogeneous. This means your pool contains only one type of object. For example, you don't want arrow and bullet to share the same pool even if they are all projectiles. We don't have c++'s decltype in c#, so if you want your object to have it's non-static member function ReturnToPool, you have to defer type evaluation to run-time (using a type dictionary). Here is the code that would possibly satisfy your need:
using System.Collections.Generic;
using UnityEngine;
using System;
public abstract class Poolable : MonoBehaviour
{
private static Dictionary<Type, Queue<Component>> objPool
= new Dictionary<Type, Queue<Component>>();
/// <summary>
/// Get an object from the pool; If fails, use the alternative method to create one
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="alternativeCreate"></param>
/// <returns></returns>
public static T Get<T>(Func<T> alternativeCreate) where T : Poolable
{
if (objPool.TryGetValue(typeof(T), out var queue) && queue.Count > 0)
{
var ret = queue.Dequeue() as T;
ret.Reactive();
return ret;
}
return alternativeCreate();
}
/// <summary>
/// Return the object to the pool
/// </summary>
public void ReturnToPool()
{
if (this.Reset())
{
var type = this.GetType();
Queue<Component> queue;
if (objPool.TryGetValue(type, out queue))
{
queue.Enqueue(this);
}
else
{
queue = new Queue<Component>();
queue.Enqueue(this);
objPool.Add(type, queue);
}
}
}
/// <summary>
/// Reset the object so it is ready to go into the object pool
/// </summary>
/// <returns>whether the reset is successful.</returns>
protected virtual bool Reset()
{
this.gameObject.SetActive(false);
return true;
}
/// <summary>
/// Reactive the object as it goes out of the object pool
/// </summary>
protected virtual void Reactivate()
{
this.gameObject.SetActive(true);
}
}
You should look into the Singleton Pattern. It's hard to suggest a suitable implementation for what you need because I don't know what you want to do with it, but basically, you can add something like this to your class:
private static Poolable _instance;
private static object _instanceLock = new Object();
public static Poolable Instance
{
get
{
if (_instance == null)
{
lock (_instanceLock)
{
if (_instance == null)
{
this._instance = [Whatever way you instantiate it];
}
}
}
return _instance;
}
}
Afterward, either make the constructor private/protected and make sure you always get your instance with Poolable.Instance.
Hope it helps!

Wrapping non-static classes in a static container [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a lot of manager classes which I use to access the database. I need to create an instance of a manager in order to access its methods.
Since I personally prefer static classes for this, I would like to know what you think of this approach:
public static class Managers
{
public static SomeManager Manager
{
get { return new SomeManager(); }
}
}
var stuff = Managers.SomeManager.DoStuff();
Any downsides?
The biggest downside to this is the lack of clarity to someone unfamiliar with your code: to me, a call like this
Managers.SomeManager.DoStuff();
means accessing SomeManager that is fixed in one way or the other, as opposed to
new SomeManager().DoStuff();
which tells me explicitly that SomeManager is being created on demand.
Converting SomeManager property into a method with an appropriate name, say, MakeSomeManager(), would restore readability:
Managers.MakeSomeManager().DoStuff();
You may want to do something like this in order to hide the process of instantiating SomeManager, the constructor of which may require some parameters that you are unwilling to carry around.
This is a bad implementation of the singleton pattern, as you are creating a new instance every time the property is called.
This would be better:
public static class Managers
{
private static SomeManager someManagerInstance;
public static SomeManager Manager
{
get
{
if (someManagerInstance == null)
{
someManagerInstance = new SomeManager();
}
return someManagerInstance;
}
}
}
Unless of course, that having a new instance every time is desired? In which case, I would wrap the creation in a method, rather than a property:
public static class Managers
{
public static SomeManager GetNewManager()
{
return new SomeManager();
}
}
Use the Singleton pattern. And if you're on .NET 4 or greater, the neatest (and 'laziest' version) is:
public sealed class SomeManager
{
private static readonly Lazy<SomeManager> lazy =
new Lazy<SomeManager>(() => new SomeManager());
public static SomeManager Instance { get { return lazy.Value; } }
private SomeManager()
{
}
}
Then access it via:
var stuff = SomeManager.Instance.DoStuff();
Implementing a thread-safe singleton has lots of pitfalls so you should check this out for some tips and examples.
You can use singleton instead, because using of static classes and methods like this is bad practice. For example try to write some unit tests for your implementation or else...
1) Create singleton class like this
public static class Singleton<T>
where T : class, new()
{
/// <summary>
/// The syncRoot.
/// </summary>
private static readonly object syncRoot = new object();
/// <summary>
/// The instance.
/// </summary>
private static volatile T instance;
/// <summary>
/// Gets the instance.
/// </summary>
public static T Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new T();
}
}
}
return instance;
}
}
}
2) Create your class like this
public class YourClass
{
/// <summary>
/// Singleton instance of
/// </summary>
public static YourClass Instance
{
get { return Singleton<YourClass>.Instance; }
}
...methods etc...
}
3) Call your singleton from code
YourClass.Instance.SomeMethodCall();

What's wrong with this singleton I created

I created a class which allows access to global access to a variable while only creating it once, essentially a singleton.
However, it doesn't match any of the 'correct' ways to implement a singleton. I assume that it's not mentioned because there is something 'wrong' with it but I can't see any problem with it other then the lack of lazy initialization.
Any thoughts?
static class DefaultFields
{
private static readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private static readonly IniConfigSource Ini = GetIni();
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private static IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public static IConfig Get()
{
return Ini.Configs["default"];
}
public static void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public static void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
It doesn't follow the usual singleton patterns as your class is static and just controls access to static variables.
Where as a singleton is normally a static single instance of a class where the only static functions are that to create and access the singleton that stores variables as normal non static member variables.
Meaning the class could quite easily be changed or made to be instanced more then once but yours cannot
You are right about the singleton, its a class with a unique instance that provides global access.
It might seem like a static class but usually its implemented in a different way.
Also bear in mind that this pattern should be used with some precaution, as its really hard to refactor out a singleton once its deep in the code. Should be used primarily when you have hardware constraints or are implemented unique points of access to a factory. I would try to avoid it whenever possible.
An example of an implementation is as follows:
public class A
{
/// <summary>
/// Unique instance to access to object A
/// </summary>
public static readonly A Singleton = new A();
/// <summary>
/// private constructor so it can only be created internally.
/// </summary>
private A()
{
}
/// <summary>
/// Instance method B does B..
/// </summary>
public void B()
{
}
}
And could be used like
A.Singleton.B()
Hope that helps.
All the methods on your class are static, so you are hiding the single instance from your users. With the singleton pattern the single instance is exposed via a public property usually called Instance (in other languages like Java it might be a method called getInstance or similar).
Your code is not wrong - it's just not the singleton pattern. If you wish to implement a singleton I would recommend Jon Skeet's article Implementing the Singleton Pattern in C#.
The biggest problem I see is that you're not doing any SyncLock-ing around writes to your INI file - multiple threads that attempt to write values at the same time could end up with unpredictable results, like both making writes and only one persisting (or multiple threads attempting to write the file at once, resulting in an IO error).
I'd create a private "Locking" object of some kind and then wrap the writes to your file in a SyncLock to ensure that only one thread at a time has the ability to change values (or, at the very least, commit changes to the INI file).
I am interested in answers to this question as well. In my opinion, there is a flood of singleton examples that use lazy instantiation, but I think you have to ask yourself if it's really necessary on a case by case basis.
Although this article pertains to Java, the concepts should still apply. This provides a number of examples for different singleton implementations. http://www.shaunabram.com/singleton-implementations/
I've also seen numerous references to the book "Effective Java", Item 71 - use lazy instantiation judiciously. Basically, don't do it unless you need to.
That's not really a singleton, it's a static class.
In many ways, static classes are similar to singleton's, true. But static classes can't implement interfaces, can't inherit functionality from a base class, and you can't carry a reference to them.
Why the readonly on the Ini field?
But if you want implement the singleton pattern, it's something like this:
static DefaultFields
{
private readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private readonly IniConfigSource Ini = GetIni();
private static DefaultFields _default;
public static DefaultFields Default
{
get { if(this._default == null){ this._default = new DefaultFields(); } return this._default; }
}
private DefaultFields()
{
}
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public IConfig Get()
{
return Ini.Configs["default"];
}
public void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
lazy initialization is very important for a singleton class. By declaring your class to be static you implement a static class, not a singleton class.

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