Skip to content

Dependency Injection

Context: A technique where an object receives its dependencies from an external source rather than creating them itself. It promotes loose coupling and testability.

public interface IGreetingService
{
string Greet(string name);
}
public class GreetingService : IGreetingService
{
public string Greet(string name) => $"Hello {name}";
}
public class Consumer
{
private readonly IGreetingService _greeting;
public Consumer(IGreetingService greeting) => _greeting = greeting;
public void Print(string name) => Console.WriteLine(_greeting.Greet(name));
}
// Simple DI container
var services = new Dictionary<Type, object>();
services[typeof(IGreetingService)] = new GreetingService();
var consumer = new Consumer((IGreetingService)services[typeof(IGreetingService)]);
consumer.Print("Alice");

ASP.NET Core built‑in DI: Services are registered in Program.cs and injected into constructors of controllers, middleware, and services. Enables unit testing by replacing real dependencies with mocks.

Example: ASP.NET Core Dependency Injection docs. Common services: ILogger<T>, DbContext, IHttpClientFactory. Also third‑party containers like Autofac, Unity.