How to Remember Dependency Injection in .NET Using Mnemonics
Dependency Injection is a design pattern used to implement Inversion of Control (IoC). It allows a class to receive its dependencies from an external source rather than creating them itself. This promotes loose coupling, making code more maintainable and testable. I also have a trick for reminding myself which has done one.
Types of Dependency Injection
- Singleton (AddSingleton)
A single instance of the service is created and shared throughout the entire application lifecycle. It is created when the application starts and remains until the application shuts down.
— Mnemonic: “Single Life” Think of a single person living in one apartment. There’s only one instance available for the entire application.
2. Scoped (AddScoped)
A new instance of the service is created for each scope (typically a single request in a web application). The same instance is used throughout the scope, but a new instance is created for each new request.
— Mnemonic: ”Scoped Scene” Imagine a theater scene where the environment (actors and set) remains the same throughout the performance, but a new environment is created for each new scene (request).
3. Transient (AddTransient)
A new instance of the service is created each time it is requested. There is no shared state between instances, meaning every request results in a fresh instance.
— Mnemonic: ”Taxi on Demand” Like calling for a taxi whenever you need one, each time you request a service, you get a new taxi (new instance).
Summary of Mnemonics
- Singleton: Single Life (One instance for the entire app)
- Scoped: Scoped Scene (One instance per request)
- Transient: Taxi on Demand (New instance every time)
These mnemonics will help you remember the key differences and functionalities of each type of dependency injection in .NET. By associating each type with a visual or situational cue, you can easily recall how and when to use them in your applications! That works for me.