Problems with the `Singleton`pattern

While studying the Singleton pattern, I came across the fact that the classical implementation of this pattern is very lame in terms of thread safety and that the Lazy implementation of would be much preferable...

Now the question itself is : is it possible to somehow combine these two implementations (the code of the attempt below) or is there any alternative option on с# that will avoid dancing with a tambourine when using this pattern .Net to the developer. A if so, wouldn't the alternative violate the principles of OOP and wouldn't it be just as difficult to use unit testing .

For example, , here - Replacing the singleton in php, where the class Singleton just makes the most common class, but the object itself, if necessary, is created using the IoC container . I would like to know the best option in this situation, thank you.

Well, an attempt to combine Lazy Loading with thread-safe implementation :

  public class Singleton
{

    public string Name { get; private set; }

    private Singleton()
    {
        Name = System.Guid.NewGuid().ToString();
    }

   public static Singleton GetInstance()
{
    return Nested.instance;
}

private class Nested
{
    internal static readonly Singleton instance = new Singleton();
}
}
Author: clyde, 2017-09-19

2 answers

The implementation from @RusGIS is correct, novotelnaya is still an example of thread-safe c msdn
https://msdn.microsoft.com/en-us/library/ff650316.aspx?f=255&MSPPError=-2147217396

using System;


public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

If you use various third-party libraries, then for this, for example, in mvvm frameworks, there are built-in tools for its implementation.

For example, MvvmCross:

            CreatableTypes()
            .EndingWith("Service")
            .AsInterfaces()
            .RegisterAsLazySingleton();

Or

Mvx.RegisterSingleton<IMyClass>(new MyClass);

You can choose.

 2
Author: Dev, 2017-09-19 07:07:01

Here is the implementation of Singleton + Lazy+ thread safety.

public sealed class LazySingleton
{
    private static readonly Lazy<LazySingleton> _instance = new Lazy<LazySingleton>(() => new LazySingleton());
    LazySingleton() {}
    public static LazySingleton Instance { get { return _instance.Value; } }
}

This implementation is taken from the book by Sergey Teplyakov "Design patterns on the .NET platform."

 5
Author: RusGIS, 2017-09-19 05:19:08