singleton design pattern – key take aways

key points

  • Antipattern – Difficult to test due to shared state – their direct static use in code…
  • doesnt follow separation of concerns
  • doesnt follow srp – coz they are responsible for managing their instance life cycle in addition to whatever their real work is
  • doesnt follow dry if you want to implement one more singleton
  • singleton classes :- can implement interfaces
  • singleton interfaces can be passed as an argument
  • singleton can use strategy design pattern and dependency injection
  • singleton instances can be assigned to variables
  • Supports polymorphism
  • can have state 
  • can be serialized
  • static classes :- cannot implement interfaces
  • static classes cannot  be passed as an arguments
  • static classes cannot use strategy design pattern and dependency injection
  • static classes cannot be assigned to variables
  • purely procedural
  • cab only access global state
  • no support for serialization
  • .net core has built in support for IOC/DI containers
  • you can configure your own or leverage their built in service collection
  • containers manage their instance lifetime
  • .net has built in support for dependency injection and lifetime management. when you register a type and its implementation you specify what lifetime to be used for that type
  • common is transient – a new instance of the type is provided any time the class requests the type as a dependency
  • Scope -the first request will get the new instance and all subsequent requests in that scope will get that same instance. In core every request that comes in is given its own scope and built in tool like EF core are designed to use a scoped lifetime. 
  • singleton – every request of that type will be given the same instance


					 public void ConfigurationServices(ServiceCollection services)  {     
 services.AddSingleton<SomeInstance>(new Someinstance());
  • A singleton class is designed to only ever have one instance created.
  • The singleton pattern makes the class itself responsible for enforcing singleton behavior
  • Its easy to get the pattern wrong when implementing it by hand
  • Lazy<T> is one of the better ways to apply the pattern
  • Singletons are different from static classes
  • IOC/DI containers are usually a better place to manage instance lifetime in .net applications.

1 thought on “singleton design pattern – key take aways”

Leave a Comment