What is DI?
Learn what dependency injection is and why it is used.
What is dependency injection?
Dependency injection (DI) means a class receives its dependencies from outside instead of creating them. For example, if Service needs an ILogger, it takes it from outside rather than calling new ConsoleLogger() internally.
This decouples classes, making them easier to test and change in small scopes. DI is a common application of Inversion of Control (IoC); control moves from the class to the container.
Inversion of Control
IoC means inversion of control: a class does not create its own dependencies; an outside container takes that job. The class only declares what it needs; the container produces and provides instances.
DI is a common application of IoC. The container resolves registered dependencies, manages their lifetimes and disposes them when needed. This gives large applications a consistent structure.
Exercise Inject a logger into Service
In Main, create a logger with ILogger logger = new ConsoleLogger();. Pass it to the service with Service s = new Service(logger);. Run with s.DoWork().
Show example solution
Create the logger with ILogger logger = new ConsoleLogger();. Create the service with Service s = new Service(logger);. Call s.DoWork();.
Example solution:
using System;
interface ILogger { void Log(string msg); }
class ConsoleLogger : ILogger
{
public void Log(string msg) => Console.WriteLine(msg);
}
class Service
{
private readonly ILogger _logger;
public Service(ILogger logger) { _logger = logger; }
public void DoWork() => _logger.Log("Working");
}
class Program
{
static void Main()
{
ILogger logger = new ConsoleLogger();
Service s = new Service(logger);
s.DoWork();
}
}
Test yourself
-
What is the main goal of DI?
- Run code faster
- Decouple classes and ease testing
- Use less memory
- Shorten compile time
Show answer
Decouple classes and ease testing — Correct. DI decouples classes and eases testing.
-
Complete the constructor injection
class Service { private readonly IRepo _repo; public Service(____ repo) { _repo = repo; } }Show answer
class Service { private readonly IRepo _repo; public Service(IRepo repo) { _repo = repo; } } -
Match the concept to its description
- DI
- Provide deps from outside
- IoC
- Inversion of control
- Container
- Manages dependencies
- Lifetime
- Sets the lifespan