Constructor Injection is the most common form of DI, where dependencies are injected through a class constructor. Here's a practical example:
Service Interface
public interface ILogger
{
void Log(string message);
}
Concrete Logger Implementation
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine($"Logging message: {message}");
}
}
Client Class with Constructor Injection
public class ClientService
{
private readonly ILogger _logger;
// Constructor Injection
public ClientService(ILogger logger)
{
_logger = logger;
}
public void Process(string data)
{
_logger.Log($"Processing data: {data}");
// Perform business logic
}
}
Dependency Injection Setup and Usage
class Program
{
static void Main(string[] args)
{
// Setup DI container (manually without a framework)
ILogger logger = new ConsoleLogger();
ClientService clientService = new ClientService(logger);
// ClientService is now ready to use with injected ILogger
clientService.Process("Sample data");
}
}