Inversion of Control (IoC)
The fundamental idea - inverting control
Inversion of Control is a design principle which says: instead of your code controlling the flow and deciding when to call dependencies itself - an external framework/container controls the flow and calls your code. Control is "inverted" - hence the name.
This is the broader principle (an architectural concept), and DI is one specific technique that implements it - this is the key relationship that is often asked about directly: "What is the difference between IoC and DI?" The answer: DI is a form of IoC, but IoC is something broader than just DI.
A classic example - the "Hollywood Principle"
IoC is sometimes called the "Hollywood Principle": "Don't call us, we'll call you".
Code WITHOUT IoC - you control the flow
class Program
{
static void Main()
{
var validator = new OrderValidator();
var repository = new OrderRepository();
var order = new Order();
// YOU decide the order, YOU call everything manually
if (validator.Validate(order))
{
repository.Save(order);
}
}
}
Here your code is the "boss" - it creates the objects, decides the order of calls, and controls the whole program flow from start to finish.
Code WITH IoC - the framework controls the flow
[ApiController]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService;
// The framework (ASP.NET Core) calls this constructor ITSELF
public OrdersController(IOrderService orderService)
{
_orderService = orderService;
}
[HttpPost]
public async Task<ActionResult> CreateOrder(Order order)
{
// The framework ITSELF decides WHEN to call this method (when an HTTP request arrives)
await _orderService.PlaceOrderAsync(order);
return Ok();
}
}
Here ASP.NET Core is the "boss":
- The framework decides when to create OrdersController (when a request arrives)
- The framework calls the constructor and injects the dependencies (this is DI - the specific technique)
- The framework decides which method to call (based on routing)
- The framework manages the object's lifetime
You don't write new OrdersController(...) anywhere in your code - you handed control over creating objects and calling your code to the framework.
IoC is more than DI - other forms of IoC
This is exactly what separates a good answer from a superficial one - IoC is realised in several different ways, and DI is just one of them:
1. Dependency Injection
The framework injects dependencies into your classes, instead of your code creating them.
2. Template Method Pattern
public abstract class OrderProcessorBase
{
// The framework/base class controls the ORDER of execution
public void Process(Order order)
{
Validate(order);
Save(order);
Notify(order);
}
// You implement ONLY the individual steps - you don't control when they are called
protected abstract void Validate(Order order);
protected abstract void Save(Order order);
protected abstract void Notify(Order order);
}
public class StandardOrderProcessor : OrderProcessorBase
{
protected override void Validate(Order order) { /* Twoja logika */ }
protected override void Save(Order order) { /* Twoja logika */ }
protected override void Notify(Order order) { /* Twoja logika */ }
}
The base class (Process) controls the order and moment of calling your methods - you only provide the implementation of individual steps. This is also IoC - inverting control over the flow, just without any DI.
3. Event-driven / Callbacks
button.Click += (sender, e) => SaveOrder(); // You write WHAT should happen
// but the FRAMEWORK (WPF) decides WHEN to call it - when the user actually clicks
This is exactly the same "callback" mechanism we talked about - and it is also a form of IoC. The WPF framework controls the message loop, detects the click, and itself calls your handler - you don't write SaveOrder() directly in Main().
4. Web frameworks in general (ASP.NET Core, the middleware pipeline)
app.Use(async (context, next) =>
{
Console.WriteLine("Przed requestem");
await next(); // you hand control back to the framework
Console.WriteLine("Po response");
});
The framework decides when to call your middleware, in what order, and when to call the next one in the chain (next()).
5. WPF Dependency Properties / Data Binding
<TextBlock Text="{Binding User.Name}" />
You don't write code that "manually" updates the TextBlock when User.Name changes - the WPF framework itself observes PropertyChanged and decides when to refresh the UI. This is also IoC - you handed control over "when to update the UI" to the framework.
A mental diagram - "who calls whom"
BEZ IoC (tradycyjny kod proceduralny):
Your code → creates objects → calls methods → controls everything
Z IoC:
Framework → creates your objects → calls your methods →
→ at the moment the framework sees fit
Why IoC is valuable - from the SOLID perspective
Going back to what we discussed at the very beginning (the Dependency Inversion Principle) - IoC is the mechanism that makes DIP possible. DIP says "depend on abstractions, not implementations" - but something has to actually deliver that concrete implementation at runtime. IoC (through the DI container) is exactly that "someone" who takes care of it, so that you (as a class) can stay innocent and depend only on the interface.
A practical answer in an interview
A good, concise answer to "what is IoC":
"IoC is a principle in which control over creating objects and over the flow of execution is handed from your code to an external framework/container - instead of you calling the dependencies, the framework calls your code. Dependency Injection is the most popular, concrete technique that implements IoC in the context of managing dependencies, but IoC also covers other mechanisms such as Template Method, event-driven programming or a middleware pipeline - the common denominator is always 'someone else controls when my code runs'."
This shows that you distinguish a general principle from a concrete implementation of that principle - exactly this kind of distinction is what they look for at the SE III level, to tell someone who "knows the names of patterns" from someone who understands why those patterns exist and how they relate to each other.