Junior — Middle
Could you explain the principle of inversion of control and its main purpose?
sobes.tech AI
Answer from AI
Inversion of Control (IoC) is a principle where the control of creating and binding objects is delegated to an external container or framework, rather than being implemented directly in the code.
The main purpose of IoC is to increase the flexibility and testability of the application, and to reduce component coupling.
Instead of the class creating dependencies itself, they are passed to it from outside (for example, through a constructor). This makes it easier to replace implementations and simplifies maintenance.
An example in C# using Dependency 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; // dependency is passed from outside
}
public void CreateUser(string name)
{
// user creation logic
_logger.Log($"User {name} created.");
}
}
Here, UserService does not create ILogger itself but receives it from outside, which implements the inversion of control principle.