Is it possible to wrap a C# singleton in an interface?

后端 未结 4 901
挽巷
挽巷 2021-02-20 05:28

I currently have a class in which I only have static members and constants, however I\'d like to replace it with a singleton wrapped in an interface.

But how can I do th

相关标签:
4条回答
  • 2021-02-20 05:35

    A solution to consider (rather than hand-rolling your own) would be to leverage an IoC container e.g. Unity.

    IoC containers commonly support registering an instance against an interface. This provides your singleton behaviour as clients resolving against the interface will receive the single instance.

      //Register instance at some starting point in your application
      container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());
    
      //This single instance can then be resolved by clients directly, but usually it
      //will be automatically resolved as a dependency when you resolve other types. 
      IActiveSessionService session = container.Resolve<IActiveSessionService>();
    

    You will also get the added advantage that you can vary the implementation of the singleton easily as it is registered against an interface. This can be useful for production, but perhaps more so for testing. True singletons can be quite painful in test environments.

    0 讨论(0)
  • 2021-02-20 05:35

    You can make all the other members of your singleton implement corresponding members in an interface. However, you are correct that the Instance property cannot be part of the interface since it is (and must remain) static.

    0 讨论(0)
  • 2021-02-20 05:49

    Interfaces can not have instances in C#, I think you only need to:

    Implement the singleton pattern (yes, you'll need a static attribute or method to get the instance, but everything else does not require to be static)

    On the other hand, your singleton can implement an interface if you want, just remember that other classes can also implement that same interface

    0 讨论(0)
  • 2021-02-20 05:55

    You can't do this with interfaces since they only specify instance methods but you can put this in a base class.

    A singleton base class:

    public abstract class Singleton<ClassType> where ClassType : new()
    {
      static Singleton()
      {
      }
    
      private static readonly ClassType instance = new ClassType();
    
      public static ClassType Instance
      {
        get
        {
          return instance;
        }
      }
    }
    

    A child singleton:

    class Example : Singleton<Example>
    {
      public int ExampleProperty { get; set; }
    }
    

    A caller:

    public void LameExampleMethod()
    {
      Example.Instance.ExampleProperty++;
    }
    
    0 讨论(0)
提交回复
热议问题