π‘ Dependency Injection in .NET
What is dependency injection and how can we achieve it in .NET API
π‘πππ©ππ§πππ§ππ² ππ§π£ππππ’π¨π§ π’π§ .πππ
Dependency injection involves providing a class with its required dependencies from an external source rather than having the class create them itself.
This helps to decouple the object creation process from the caller, leading to a more modular and flexible system.
In other words, it allows a class to focus on its core functionality rather than worrying about how to create and manage its dependencies.
ππ‘π² ππ¨ π°π π§πππ πππ©ππ§πππ§ππ² π’π§π£ππππ’π¨π§?
By using DI classes are decoupled from each other so you make changes at one place and it is reflected all over the places.
ππ¨π° ππ¨ π’π¦π©π₯ππ¦ππ§π πππ©ππ§πππ§ππ² π’π§π£ππππ’π¨π§?
β
In .NET 6 we implement DI in Program.cs class by using builder dot Services
β
For previous versions of .NET, to implement DI we need to add the service in βConfigureServicesβ method which is in Startup.cs file
ππ’ππππ«ππ§π π°ππ²π¬ π¨π π’π¦π©π₯ππ¦ππ§ππ’π§π πππ©ππ§πππ§ππ² ππ§π£ππππ’π¨π§
There are three ways of doing DI:
1.Scoped β‘οΈ It will create an instance per scope, if we are in same scope same instance would be used. Whenever we go out of scope new instance would be created.
2. Transient β‘οΈ It creates new instances every time its injected.
3. Singleton β‘οΈ It instantiates one global object for all requests coming to the server from any user.
πππ§πππ’ππ¬ π¨π πππ©ππ§πππ§ππ² ππ§π£ππππ’π¨π§
1.Improved testability: Dependency injection makes it easier to write unit tests for your code, as you can easily substitute mock objects for the real dependencies.
2. Enhanced flexibility: By injecting dependencies from the outside, you can easily change the implementation of a class's dependencies without having to modify the class itself. This makes it easier to adapt your application to changing requirements.
3. Increased modularity: Dependency injection encourages the use of small, single-purpose classes that are easy to test and reuse in different contexts. This can lead to a more modular and maintainable codebase.
4. Better separation of concerns: Dependency injection helps to separate the concerns of different parts of your application, making it easier to understand and maintain the code.
5. Enhanced decoupling: Dependency injection promotes loose coupling between classes, which can make your application more resilient to change and easier to test.