IoC (DI) Container in .NET Core - Explained with Example

πŸ’‘ Concept Name

IoC (Inversion of Control) Container

πŸ“˜ Quick Intro

An IoC Container in .NET Core handles object creation and dependency resolution, promoting loose coupling through Dependency Injection (DI). The framework's built-in container is configured via Microsoft.Extensions.DependencyInjection.

🧠 Analogy / Short Story

Imagine a switchboard. You plug in your appliances and get power without worrying about how electricity is generated. The IoC container is like that switchboardβ€”it knows how to give you what you need (dependencies), without you managing the wiring (instantiation).

πŸ”§ Technical Explanation

  • The built-in IoC container manages service lifetimes and resolution.
  • It supports Transient, Scoped, and Singleton lifetimes.
  • Services are registered in Program.cs using builder.Services.Add* methods.
  • It injects dependencies automatically into controllers, services, and components.

🎯 Purpose & Use Case

  • βœ… Avoid manual instantiation with new keyword
  • βœ… Decouple components using interfaces
  • βœ… Centralized service registration
  • βœ… Better unit testing with mocks
  • βœ… Manages lifecycle and disposal of services

πŸ’» Real Code Example

// Service interface
public interface IGreetingService {
    string Greet();
}

// Implementation
public class GreetingService : IGreetingService {
    public string Greet() => ""Hello from IoC!"";
}

// Register in Program.cs
builder.Services.AddScoped<IGreetingService, GreetingService>();

// Inject in Controller
public class HomeController : Controller {
    private readonly IGreetingService _greetingService;
    public HomeController(IGreetingService greetingService) {
        _greetingService = greetingService;
    }
    public IActionResult Index() => Content(_greetingService.Greet());
}

❓ Interview Q&A

Q1: What is an IoC container?
A: A framework that handles object creation and dependency injection.

Q2: Which namespace provides IoC in .NET Core?
A: Microsoft.Extensions.DependencyInjection

Q3: What are the types of lifetimes supported?
A: Transient, Scoped, Singleton

Q4: What does AddScoped mean?
A: Creates a new instance per request.

Q5: How is IoC related to DI?
A: IoC is the principle; DI is the implementation technique.

Q6: How to register a service in .NET Core?
A: Use builder.Services.AddScoped/AddTransient/AddSingleton

Q7: Can you override the default IoC container?
A: Yes, with third-party containers like Autofac

Q8: Is IoC used in middleware?
A: Yes, dependencies can be injected into middleware

Q9: Can we register multiple implementations for one interface?
A: Yes, and inject IEnumerable<T>

Q10: Where is the IoC setup done in minimal hosting model?
A: In Program.cs via builder.Services

πŸ“ MCQs

Q1. What is the purpose of IoC container in .NET Core?

  • To create UI
  • To compile code
  • To manage object creation and dependency injection
  • To load static files

Q2. Which method registers a scoped service?

  • AddTransient
  • AddSingleton
  • AddScoped
  • RegisterScoped

Q3. Where do you register services in .NET Core?

  • Startup.cs
  • appsettings.json
  • Program.cs
  • Web.config

Q4. What is the default IoC container in .NET Core?

  • Autofac
  • Unity
  • SimpleInjector
  • Microsoft.Extensions.DependencyInjection

Q5. What does AddSingleton do?

  • Registers per request
  • Creates new instance every time
  • Registers a single shared instance
  • Registers as global service

Q6. What happens if a required service is not registered?

  • Service is auto-created
  • App throws runtime exception
  • Service is ignored
  • Compiler error

Q7. Which lifetime is best for stateless short-lived services?

  • Singleton
  • Scoped
  • Transient
  • Static

Q8. Can middleware receive dependencies from IoC container?

  • No
  • Only controllers
  • Yes
  • Only Razor pages

Q9. How do you inject dependencies into controllers?

  • Static method
  • GetService()
  • Constructor injection
  • app.Run()

Q10. What pattern does IoC support?

  • Decorator
  • Adapter
  • Inversion of Control
  • Singleton

πŸ’‘ Bonus Insight

Always code to interfaces when registering services. It increases testability and allows you to switch implementations without breaking the rest of the codebase.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: