Dependency Injection Flashcards
What is DI
a programming technique that makes a class independent of its dependencies DI achieves inversion of control (IoC)
How does DI work
by decoupling the usage of an object from its creation
What problem does DI address
SOLID design principles to improve reusability of code and reduce the frequency with which you need to change a class
How does DI accomplish its goal(s)
by decoupling the creation of the usage of an object. That enables you to replace dependencies without changing the class that uses them.
Dependencies are configured at run-time.
It also reduces the risk that you have to change a class just because one of its dependencies changed.
What is an alternative to DI
The service locator pattern
Role 1 in DI
A service you want to use
Role 2 in DI
A client that uses the service
Role 3 in DI
An interface that is used by the client and implements the service
Role 4 in DI
An injector which creates a service instance and injects it into the client
What is the difference between dependency inversion and DI
Dependency inversion includes roles 1-3 in DI but not the fourth
What does constructor injection allow
Constructor injection enables you to replace the compile time dependency to a specific implementation class with a runtime dependency to any implementation class.
Setter Injection
Allows you to remove dependency through the properties of a class
Interface-based Injection
Injection is made directly into a class through a method
Service Lifetimes
Transient, Scoped, Singleton
Service Lifetime - Transient
Transient lifetime services are created each time they’re requested from the service container. This lifetime works best for lightweight, stateless services. Register transient services with AddTransient.