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

后端 未结 4 886
挽巷
挽巷 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(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();
    

    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.

提交回复
热议问题