Dependency Injection in .NET Core - Explained with Example

πŸ’‘ Concept Name

Dependency Injection (DI)

πŸ“˜ Quick Intro

Dependency Injection (DI) is a technique to achieve Inversion of Control (IoC) between classes and their dependencies. In .NET Core, DI is built-in and enables loose coupling and easier testing.

🧠 Analogy / Short Story

Imagine a coffee machine. Instead of the machine making beans itself, it receives beans from outside. This makes it flexible. If you want espresso beans or decaf, you just change the input. DI works the same wayβ€”it injects the required parts instead of hardcoding them.

πŸ”§ Technical Explanation

.NET Core provides a built-in DI container. You register services in Program.cs using methods like AddSingleton, AddScoped, or AddTransient. The framework handles the object lifecycle and injects dependencies where needed.

🎯 Purpose & Use Case

  • βœ… Reduces tight coupling between components
  • βœ… Improves unit testing and mocking
  • βœ… Centralized service management
  • βœ… Supports various lifetimes for services

πŸ’» Real Code Example

Simple Service Injection:

// IService.cs
public interface IMessageService {
    string GetMessage();
}

// Service Implementation
public class MessageService : IMessageService {
    public string GetMessage() => "Hello from service!";
}

// Program.cs
builder.Services.AddScoped();

// Controller
public class HomeController : Controller {
    private readonly IMessageService _service;
    public HomeController(IMessageService service) => _service = service;
    public IActionResult Index() => Content(_service.GetMessage());
}

❓ Interview Q&A

Q1: What is Dependency Injection?
A: A design pattern that injects dependencies instead of creating them internally.

Q2: Types of service lifetimes?
A: Transient, Scoped, Singleton.

Q3: What method is used to register services in DI container?
A: AddSingleton, AddScoped, or AddTransient.

Q4: Which lifetime creates a new instance every time?
A: Transient.

Q5: How does DI help with unit testing?
A: You can mock injected services.

Q6: Can constructor take multiple services?
A: Yes, constructor injection allows multiple dependencies.

Q7: Is DI container replaceable in ASP.NET Core?
A: Yes, you can use others like Autofac.

Q8: Where do you register DI in ASP.NET Core 6+?
A: In Program.cs inside the builder.Services collection.

Q9: What is the default DI container in ASP.NET Core?
A: Microsoft.Extensions.DependencyInjection.

Q10: Difference between Scoped and Singleton?
A: Scoped creates one instance per request; Singleton uses the same for the app lifetime.

πŸ“ MCQs

Q1. What is the primary purpose of Dependency Injection in .NET Core?

  • To write unit tests
  • To create models
  • To promote loose coupling
  • To improve UI design

Q2. Which service lifetime creates a new instance every time it is requested?

  • Singleton
  • Scoped
  • Transient
  • Global

Q3. Which lifetime creates a single instance per request in ASP.NET Core?

  • Transient
  • Singleton
  • Scoped
  • Static

Q4. Which method is used to register services in Program.cs?

  • builder.Inject()
  • ConfigureServices()
  • RegisterServices()
  • builder.Services.Add*

Q5. Which interface is used to inject a service in a controller?

  • Service Injection
  • Field Injection
  • Constructor Injection
  • Property Injection

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

  • Compiler error
  • It works with null values
  • Application throws an exception at runtime
  • It logs a warning and continues

Q7. Which of the following is true about Singleton lifetime?

  • Creates a new instance per request
  • Used only in testing
  • Same instance is used throughout application lifetime
  • Only works in Blazor

Q8. Where are services typically registered in a .NET Core web app?

  • appsettings.json
  • Controller
  • Program.cs or Startup.cs
  • launchSettings.json

Q9. Which of the following can be injected using DI?

  • Configuration
  • Logging
  • Custom services
  • All of the above

Q10. What does `AddSingleton<IService, Service>()` do?

  • Adds a scoped service
  • Creates new instance each time
  • Registers a single shared instance
  • Registers for transient lifecycle

πŸ’‘ Bonus Insight

Use interfaces for services so they’re easier to mock and swap. Always avoid using new keyword in business logic if you plan to use DIβ€”it defeats the purpose of decoupling.

πŸ“„ PDF Download

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

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

Tags: