Junior — Middle
Can you explain the principle of dependency injection in software development?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a principle where an object receives its dependencies (such as other objects or services) from outside, rather than creating them itself. This increases modularity, simplifies testing, and supports easier maintenance of the code.
In C#, this is often implemented through the class constructor, properties, or methods where the necessary dependencies are passed in. For example:
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger
{
public void Log(string message) => Console.WriteLine(message);
}
public class UserService
{
private readonly ILogger _logger;
// Dependency injection via constructor
public UserService(ILogger logger)
{
_logger = logger;
}
public void CreateUser(string name)
{
// user creation logic
_logger.Log($"User {name} created.");
}
}
// Usage
var logger = new ConsoleLogger();
var service = new UserService(logger);
service.CreateUser("Alice");
Thus, UserService does not depend on a specific logger implementation, which makes replacement and testing easier.