Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?

like image 543
Surfbutler Avatar asked Dec 20 '10 16:12

Surfbutler


People also ask

Should I wrap my AC lines?

Without insulation around the low-pressure refrigerant line, condensation may form. The low-pressure refrigerant line will develop condensation that can cause moisture damage. To protect against condensation, the low-pressure refrigerant should be insulated.

Does insulating AC lines help?

Insulation benefits and recommended type for AC: In refrigeration and air-conditioning applications, insulation needs to be able to protect against condensation. Moisture control is critical to thermal efficiency. If moisture intrudes the insulating material surrounding cold-water piping, thermal efficiency is lost.

Which refrigerant lines should be insulated?

Identify the Correct AC Line to Insulate The large cold copper pipe (the suction line) and the small warm tube (the liquid line). You should only insulate the larger (suction line) pipe. The smaller pipe does not require insulation because it is designed to disperse some of the heat as it travels inside.


1 Answers

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.

like image 156
Tim Lloyd Avatar answered Oct 14 '22 01:10

Tim Lloyd