Managing Dependencies with Dependency Injection in .NET
Managing Dependencies with Dependency Injection (DI) in .NET is a core principle for building maintainable, testable, and modular applications. .NET has built-in support for DI via its Microsoft.Extensions.DependencyInjection library, which is widely used across ASP.NET Core, console apps, worker services, and more.
🔧 What is Dependency Injection?
Dependency Injection is a design pattern in which an object receives its dependencies from an external source rather than creating them itself.
Without DI:
csharp
Copy
Edit
public class OrderService
{
private readonly EmailSender _emailSender = new EmailSender(); // Tightly coupled
}
With DI:
csharp
Copy
Edit
public class OrderService
{
private readonly IEmailSender _emailSender;
public OrderService(IEmailSender emailSender) // Dependency injected
{
_emailSender = emailSender;
}
}
🚀 Using DI in .NET
Step 1: Define Interfaces
csharp
Copy
Edit
public interface IEmailSender
{
void Send(string to, string subject, string body);
}
Step 2: Implement the Interface
csharp
Copy
Edit
public class EmailSender : IEmailSender
{
public void Send(string to, string subject, string body)
{
// Logic to send email
}
}
Step 3: Register Services in the DI Container
In Program.cs (ASP.NET Core or .NET Generic Host):
csharp
Copy
Edit
builder.Services.AddScoped<IEmailSender, EmailSender>();
builder.Services.AddScoped<OrderService>();
AddTransient<T>(): New instance each time.
AddScoped<T>(): One instance per request/scope.
AddSingleton<T>(): Single instance for the app lifetime.
Step 4: Inject Dependencies
In Controllers or Services:
csharp
Copy
Edit
public class OrderController : Controller
{
private readonly OrderService _orderService;
public OrderController(OrderService orderService)
{
_orderService = orderService;
}
}
🧪 Dependency Injection in Unit Tests
You can easily mock dependencies using interfaces:
csharp
Copy
Edit
var mockEmailSender = new Mock<IEmailSender>();
var service = new OrderService(mockEmailSender.Object);
🛠 Advanced Features
1. Constructor Injection (Default)
Most common and preferred approach.
2. Method Injection
Used for optional or scoped services.
csharp
Copy
Edit
public void Process([FromServices] IEmailSender sender)
{
sender.Send(...);
}
3. Property Injection
Less common, possible with service locators.
⚠️ Common Pitfalls
Avoid Service Locator Pattern: Don’t use IServiceProvider.GetService<T>() frequently — it defeats DI’s purpose.
Watch for Scoped Service Lifetimes: Injecting scoped services into singletons causes runtime exceptions.
Avoid Too Many Dependencies: If a constructor has many parameters, your class might be doing too much — consider refactoring.
✅ Summary
Concept Description
Interface Decouples implementation from usage
Service Lifetime Controls how often a service instance is created
Registration Done in Program.cs or Startup.cs using Add* methods
Injection Types Constructor (preferred), Method, Property
Testability Easy with mocks and interface-driven design
Learn Full Stack Dot NET Training in Hyderabad
Read More
Error Handling and Logging in ASP.NET Core Applications
Implementing Authentication and Authorization in .NET Core Apps
How to Use Entity Framework Core for Database Management in Full Stack .NET
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment