DEV Community

lokesh
lokesh

Posted on

Stop Hardcoding! Master Dependency Injection in .NET 8/9 like a Pro

Introduction
As a .NET Developer with 2 years of experience, I’ve seen many beginners struggle with "Tight Coupling." If you are hardcoding your classes using the new keyword everywhere, your code is a nightmare to test and maintain.

Today, let’s break down Dependency Injection (DI) in the simplest way possible.

What is Dependency Injection?
In simple terms: Instead of a class "creating" its own tools, we "inject" the tools it needs from the outside.

The Problem: Tight Coupling ❌
Look at this code. Here, UserService is tightly coupled with EmailService. If I want to change the email provider, I have to change the UserService code.


The Solution: Dependency Injection
We use an Interface to decouple the classes.

  1. Create an Interface

  1. Inject via Constructor Now, UserService doesn't care which email service it uses, as long as it follows the IEmailService rule.

Understanding Service Lifetimes
In .NET Core, we have three main ways to register these services in Program.cs. This is a top interview question!

Transient: A new instance is created every time it is requested.

Scoped: A new instance is created once per client request (perfect for Database Context).

Singleton: Only one instance is created for the entire lifetime of the application.

Registration in Program.cs

Conclusion
Dependency Injection makes your code:

Testable: You can easily swap real services with "Mocks."

Maintainable: Changes in one class don't break others.

Scalable: Clean Architecture follows this as a core rule.

What is your favorite DI lifetime? Let me know in the comments!

dotnet #csharp #webdev #programming #tutorial

Top comments (0)