Explain dependency injection In c#
- User
Explain dependency injection In c#
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Explain dependency injection In c#
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Dependency Injection is a design pattern that lets objects receive (“inject”) their dependencies from an external source rather than creating them internally.
In C#—especially in modern .NET (Core, 5/6/7/8)—DI is a first-class citizen thanks to the built-in IoC (Inversion of Control) container found in Microsoft.Extensions.DependencyInjection.
| Without DI (Tightly Coupled) | With DI (Loosely Coupled) |
|---|---|
Classes instantiate their collaborators directly (new FooService()) | Classes depend on abstractions (usually interfaces) provided from the outside |
| Hard to unit-test (real DB, SMTP, …) | Easy to swap real implementation for mocks/stubs |
| Changing implementation requires code changes everywhere | Implementation can be swapped by editing the composition root (startup/registration) |
| Violates Single Responsibility (class handles both logic and wiring) | Clear separation of concerns: logic vs. object graph construction |
ILogger, ICustomerRepository).Constructor Injection (most common)
public class OrderProcessor
{
private readonly IPaymentService _payments;
private readonly ILogger<OrderProcessor> _logger;
public OrderProcessor(IPaymentService payments,
ILogger<OrderProcessor> logger)
{
_payments = payments;
_logger = logger;
}
public void Process(Order order) { /* ... */ }
}
Property (Setter) Injection
public class EmailSender
{
public ISmtpClient SmtpClient { get; set; } // set by container
}
Method Injection
public class ReportJob
{
public void Run(IReportGenerator generator,
ILogger<ReportJob> log)
{ /* ... */ }
}
(Less common—harder for DI containers to discover automatically.)
// Program.cs (ASP.NET Core, .NET 6 minimal hosting)
var builder = WebApplication.CreateBuilder(args);
// 1. Register services
builder.Services.AddTransient<IPaymentService, StripePaymentService>();
builder.Services.AddScoped<ICustomerRepository, SqlCustomerRepository>();
builder.Services.AddSingleton<IClock, SystemClock>();
// Add MVC, logging, etc.
builder.Services.AddControllers();
var app = builder.Build();
// 2. Use services (resolved automatically by framework)
app.MapControllers();
app.Run();
Lifetimes:
Transient – new instance every timeScoped – one per HTTP request / scopeSingleton – one for the entire applicationpublic interface IGreeter
{
string Greet(string name);
}
public class ConsoleGreeter : IGreeter
{
public string Greet(string name) => $"Hello, {name}!";
}
public class GreeterConsumer
{
private readonly IGreeter _greeter;
// Constructor Injection
public GreeterConsumer(IGreeter greeter)
{
_greeter = greeter;
}
public void SayHello() =>
Console.WriteLine(_greeter.Greet("DI World"));
}
class Program
{
static void Main()
{
// Manual composition root
var services = new ServiceCollection();
services.AddSingleton<IGreeter, ConsoleGreeter>();
services.AddTransient<GreeterConsumer>();
using var provider = services.BuildServiceProvider();
var consumer = provider.GetRequiredService<GreeterConsumer>();
consumer.SayHello();
}
}
Output:
Hello, DI World
[Fact]
public void Processor_Uses_MockPaymentService()
{
var paymentMock = new Mock<IPaymentService>();
var logMock = new Mock<ILogger<OrderProcessor>>();
var processor = new OrderProcessor(paymentMock.Object, logMock.Object);
processor.Process(new Order());
paymentMock.Verify(p => p.Pay(...), Times.Once);
}
Because the dependencies are abstractions, you can inject mocks without changing OrderProcessor.
Although the built-in container is adequate for 90 % of cases, other mature containers offer advanced features (interception, child scopes, conventions):
• Autofac
• SimpleInjector
• Ninject
• StructureMap (now Lamar)
• Castle Windsor
Usage pattern is always the same: register ⇒ resolve ⇒ inject.
var svc = provider.GetService<IFoo>() sprinkled throughout your code. This hides dependencies instead of making them explicit.Dependency Injection in C#:
✔ Promotes loose coupling and SOLID principles
✔ Is natively supported through Microsoft.Extensions.DependencyInjection
✔ Makes testing and maintenance simpler
✔ Can be applied via constructor, property, or method injection
✔ Relies on an IoC container for registration and resolution
Once you grasp the flow—register, resolve, inject—DI becomes an indispensable tool in building clean, modular, and testable .NET applications. Happy injecting! 🚀