Sobes.tech
Junior — Middle

What is the role and advantages of using Dependency Injection in programming?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a design pattern where an object's dependencies are provided from outside rather than created internally.

Role of DI:

  • Allows separation of object creation from their usage.
  • Simplifies management of dependencies between classes.
  • Increases modularity and testability of code.

Advantages:

  • Improved testability: dependencies can be easily replaced with mocks or stubs.
  • Reduced coupling: classes do not depend on specific implementations but work with abstractions.
  • Simplified maintenance: changes in dependencies do not require modifications in classes that use them.

Example in C# using constructor injection:

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;
    public UserService(ILogger logger) { _logger = logger; }
    public void CreateUser(string name) {
        // user creation logic
        _logger.Log($"User {name} created.");
    }
}

// Dependency injection
var logger = new ConsoleLogger();
var service = new UserService(logger);
service.CreateUser("Alice");

Here, UserService does not create ConsoleLogger itself but receives it from outside, making it easier to replace the logger if needed.

What is the role and advantages of using Dependency… - sobes.tech