如何在c#中实现单例?

时间:2022-06-01 19:34:32

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.

如何在c#中实现单例模式?我想把常数和一些基本的函数放在里面因为我在我的项目中到处都用到它们。我希望它们是“全局的”,而不需要手动将它们绑定到我创建的每个对象。

16 个解决方案

#1


28  

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.

当您有一个具有状态的普通类时,Singleton是最有用的,但是您只需要其中的一个。其他人提供的链接在探索单例模式时应该是有用的。

#2


7  

Singleton != Global. You seem to be looking for the keyword static.

单例! =全球。你似乎在寻找关键词static。

#3


4  

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; }
    }

#4


4  

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 aboiut implementing the pattern.

为什么需要依赖注入框架来获得单例?对于某些企业应用程序来说,使用IOC容器是可以的(当然,前提是它不会被过度使用),但是,啊,小伙子只想知道如何实现这个模式。

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...

为什么不总是热切地实例化,然后提供一个返回静态的方法,上面编写的大部分代码就会消失。遵循C2那句古老的格言——做那些有可能成功的事情……

#5


4  

Singletons only make sense if both of these conditions are true:

只有当这两种情况都是正确的时,单例才有意义:

  1. The object must be global
  2. 对象必须是全局的。
  3. There must only ever exist a single instance of the object
  4. 对象的实例必须只有一个

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.

注意,#2并不意味着您希望对象只有一个实例——如果是这样,只需实例化它一次——它意味着必须(如在,不为真是危险的)只有一个实例。

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.

如果您想要全局变量,只需创建一个(非signleton)对象的全局实例(或使其为静态对象)。如果你只想要一个实例,静态就是你的朋友。另外,只实例化一个对象。

Thats my opinion anyway.

这是我的观点。

#6


3  

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.

我建议您阅读MSDN上探索单例设计模式的文章。它详细描述了框架的特性,使模式易于实现。

As an aside, I'd check out the related reading on SO regarding Singletons.

顺便说一句,我想看看关于单身的相关阅读资料。

#7


3  

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() {

    }

}

#8


3  

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/.

如果您想要一个松散耦合的设计,静态单例几乎就是一个反模式。如果可能的话,尽量避免使用,除非这是一个非常简单的系统,否则我建议您看看可用的许多依赖注入框架中的一个,比如http://ninject.org/或http://code.google.com/p/autofac/。

To register / consume a type configured as a singleton in autofac you would do something like the following:

要注册/使用在autofac中配置为singleton的类型,您需要做如下操作:

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.

顺便说一句,公认的答案是一个糟糕的解决方案,至少要检查那些真正实现该模式的人。

#9


2  

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); }
    }

}

#10


2  

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.

这将为您提供一个实例(以正确的方式实例化),并且实际上是惰性的,因为在调用Build()之前不会调用静态构造函数。

#11


1  

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.

问问你自己:“如果这个类有多个实例,它会不会中断?”如果答案是否定的,那么就不需要单例。

#12


1  

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.

嗯…与相关函数相关的常量很少……难道这不是最好的办法吗?我知道您可以在Java中使用方法和所有方法创建一个自定义枚举,在c#中应该可以实现,如果不直接支持,那么可以使用带有私有构造函数的简单类singleton来实现。

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.

如果您的常量与语义相关,您应该考虑enums(或等效概念),您将获得const静态变量的所有优点,您将能够利用编译器的类型检查。

My 2 cent

我2分

#13


1  

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.

就我个人而言,我倾向于使用依赖注入框架,比如Unity,它们都能够在容器中配置单元素,并且通过从类依赖关系转移到接口依赖关系来改善耦合。

#14


0  

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();
    }   
}

#15


0  

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.

我使用Singleton模式为我的项目编写了一个类。它很容易使用。希望它对你有用。请找到下面的代码。

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();
    }

#16


0  

In c# it could be (Thread safe as well as lazy initialization):

在c#中,它可以是(线程安全以及延迟初始化):

public sealed class MySingleton
{
    static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
    public static MySingleton Instance => _instance.Value;
    private MySingleton() { }
}

#1


28  

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.

当您有一个具有状态的普通类时,Singleton是最有用的,但是您只需要其中的一个。其他人提供的链接在探索单例模式时应该是有用的。

#2


7  

Singleton != Global. You seem to be looking for the keyword static.

单例! =全球。你似乎在寻找关键词static。

#3


4  

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; }
    }

#4


4  

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 aboiut implementing the pattern.

为什么需要依赖注入框架来获得单例?对于某些企业应用程序来说,使用IOC容器是可以的(当然,前提是它不会被过度使用),但是,啊,小伙子只想知道如何实现这个模式。

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...

为什么不总是热切地实例化,然后提供一个返回静态的方法,上面编写的大部分代码就会消失。遵循C2那句古老的格言——做那些有可能成功的事情……

#5


4  

Singletons only make sense if both of these conditions are true:

只有当这两种情况都是正确的时,单例才有意义:

  1. The object must be global
  2. 对象必须是全局的。
  3. There must only ever exist a single instance of the object
  4. 对象的实例必须只有一个

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.

注意,#2并不意味着您希望对象只有一个实例——如果是这样,只需实例化它一次——它意味着必须(如在,不为真是危险的)只有一个实例。

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.

如果您想要全局变量,只需创建一个(非signleton)对象的全局实例(或使其为静态对象)。如果你只想要一个实例,静态就是你的朋友。另外,只实例化一个对象。

Thats my opinion anyway.

这是我的观点。

#6


3  

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.

我建议您阅读MSDN上探索单例设计模式的文章。它详细描述了框架的特性,使模式易于实现。

As an aside, I'd check out the related reading on SO regarding Singletons.

顺便说一句,我想看看关于单身的相关阅读资料。

#7


3  

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() {

    }

}

#8


3  

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/.

如果您想要一个松散耦合的设计,静态单例几乎就是一个反模式。如果可能的话,尽量避免使用,除非这是一个非常简单的系统,否则我建议您看看可用的许多依赖注入框架中的一个,比如http://ninject.org/或http://code.google.com/p/autofac/。

To register / consume a type configured as a singleton in autofac you would do something like the following:

要注册/使用在autofac中配置为singleton的类型,您需要做如下操作:

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.

顺便说一句,公认的答案是一个糟糕的解决方案,至少要检查那些真正实现该模式的人。

#9


2  

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); }
    }

}

#10


2  

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.

这将为您提供一个实例(以正确的方式实例化),并且实际上是惰性的,因为在调用Build()之前不会调用静态构造函数。

#11


1  

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.

问问你自己:“如果这个类有多个实例,它会不会中断?”如果答案是否定的,那么就不需要单例。

#12


1  

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.

嗯…与相关函数相关的常量很少……难道这不是最好的办法吗?我知道您可以在Java中使用方法和所有方法创建一个自定义枚举,在c#中应该可以实现,如果不直接支持,那么可以使用带有私有构造函数的简单类singleton来实现。

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.

如果您的常量与语义相关,您应该考虑enums(或等效概念),您将获得const静态变量的所有优点,您将能够利用编译器的类型检查。

My 2 cent

我2分

#13


1  

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.

就我个人而言,我倾向于使用依赖注入框架,比如Unity,它们都能够在容器中配置单元素,并且通过从类依赖关系转移到接口依赖关系来改善耦合。

#14


0  

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();
    }   
}

#15


0  

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.

我使用Singleton模式为我的项目编写了一个类。它很容易使用。希望它对你有用。请找到下面的代码。

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();
    }

#16


0  

In c# it could be (Thread safe as well as lazy initialization):

在c#中,它可以是(线程安全以及延迟初始化):

public sealed class MySingleton
{
    static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
    public static MySingleton Instance => _instance.Value;
    private MySingleton() { }
}