NET Centric Computing · Unit 5
Dependency Injection and Application Configuration
Exam-focused notes for Dependency Injection and Application Configuration (NET Centric Computing, BIT351): what the TU syllabus asks and how it has actually been tested, with 2 solved past questions from this unit.
Dependency Injection and Application Configuration in short
Real applications are built from many classes that depend on each other. Dependency injection keeps those classes loosely connected, which makes them easy to change and test. This chapter also shows how to build, run and test a .NET Core project.
What this unit covers
- Dependency injection principles
- IOC container
- Creating controllers with DI
- Creating actions with DI
- Building and running .NET Core applications
- Testing .NET Core applications
Dependency injection principles
2081.1 · 10 marks
What do you mean by dependency injection and IOC container? Describe the methods for creating controller and action with example.[10]
Show solved answerHide answer
Dependency Injection and IOC Container in ASP.NET MVC
Note: The reference notes were not available for this topic. The following answer is based on standard ASP.NET MVC / .NET Core curriculum content as taught in TU BSc CSIT.
1. Dependency Injection (DI)
Dependency Injection is a design pattern and a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Instead of a class creating its own dependencies (objects it needs), those dependencies are injected from outside, typically through a constructor, property, or method.
Why DI?
- Reduces tight coupling between classes
- Makes code more testable, maintainable, and reusable
- Follows the Dependency Inversion Principle (SOLID)
Types of Dependency Injection
| Type | Description |
|---|---|
| Constructor Injection | Dependencies passed through the constructor |
| Property Injection | Dependencies set through public properties |
| Method Injection | Dependencies passed as method parameters |
Example Without DI (Tightly Coupled)
public class StudentController : Controller
{
private StudentRepository _repo = new StudentRepository(); // tight coupling
}
Example With DI (Loosely Coupled)
public class StudentController : Controller
{
private readonly IStudentRepository _repo;
// Constructor Injection
public StudentController(IStudentRepository repo)
{
_repo = repo;
}
public IActionResult Index()
{
var students = _repo.GetAll();
return View(students);
}
}
2. IOC Container (Inversion of Control Container)
An IoC Container (also called a DI Container) is a framework or component that:
- Manages the creation and lifetime of objects (dependencies)
- Automatically injects dependencies wherever required
- Maintains a registry of interfaces and their concrete implementations
In ASP.NET Core, the built-in IoC container is accessed through IServiceCollection in Program.cs or Startup.cs.
Service Lifetimes in IoC Container
| Lifetime | Method | Description |
|---|---|---|
| Transient | AddTransient<>() | New instance every time it is requested |
| Scoped | AddScoped<>() | One instance per HTTP request |
| Singleton | AddSingleton<>() | One instance for the entire application lifetime |
Registering Services in IoC Container (ASP.NET Core)
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Register services in IoC container
builder.Services.AddScoped<IStudentRepository, StudentRepository>();
builder.Services.AddTransient<IEmailService, EmailService>();
builder.Services.AddSingleton<ILoggerService, LoggerService>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapDefaultControllerRoute();
app.Run();
When StudentController is requested, the IoC container automatically resolves IStudentRepository and injects StudentRepository.
3. Creating Controllers in ASP.NET MVC
A Controller is a class that:
- Handles incoming HTTP requests
- Processes user input
- Returns appropriate responses (Views, JSON, Redirects, etc.)
Rules for Creating a Controller
- The class name must end with the suffix Controller (e.g.,
HomeController) - It must inherit from the Controller base class (or
ControllerBasefor APIs) - It must be placed in the Controllers folder (by convention)
- It must be a public class
Methods of Creating a Controller
Method 1: Inheriting from Controller Class
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Method 2: Using Dependency Injection in Controller
using Microsoft.AspNetCore.Mvc;
public class ProductController : Controller
{
private readonly IProductService _productService;
// Constructor Injection via IoC Container
public ProductController(IProductService productService)
{
_productService = productService;
}
public IActionResult Index()
{
var products = _productService.GetAllProducts();
return View(products);
}
}
Method 3: API Controller (inheriting ControllerBase)
[ApiController]
[Route("api/[controller]")]
public class StudentApiController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
return Ok(new { message = "All Students" });
}
}
4. Creating Action Methods
An Action Method is a public method inside a controller that:
- Responds to a specific HTTP request (GET, POST, PUT, DELETE)
- Returns an
IActionResult(or specific result types)
Types of Action Results
| Return Type | Method | Description |
|---|---|---|
ViewResult | View() | Returns an HTML view |
RedirectResult | Redirect() | Redirects to a URL |
JsonResult | Json() | Returns JSON data |
ContentResult | Content() | Returns plain text |
NotFoundResult | NotFound() | Returns 404 |
Example: Various Action Methods
public class StudentController : Controller
{
private readonly IStudentRepository _repo;
public StudentController(IStudentRepository repo)
{
_repo = repo;
}
// GET: /Student/Index
[HttpGet]
public IActionResult Index()
{
var students = _repo.GetAll();
return View(students); // returns a View
}
// GET: /Student/Details/5
[HttpGet]
public IActionResult Details(int id)
{
var student = _repo.GetById(id);
if (student == null)
{
return NotFound(); // returns 404
}
return View(student);
}
// POST: /Student/Create
[HttpPost]
public IActionResult Create(Student student)
{
if (!ModelState.IsValid)
{
return View(student); // redisplay the form with errors
}
_repo.Add(student);
return RedirectToAction("Index"); // redirect after POST
}
// GET: /Student/Json
[HttpGet]
public IActionResult GetJson()
{
return Json(_repo.GetAll()); // returns JSON data
}
}
Notice that IStudentRepository is never created with new inside the controller: the IoC container sees the constructor parameter, resolves the registered implementation and injects it, which is constructor injection in practice.
Conclusion
Dependency injection means a class receives the services it needs from outside instead of constructing them itself, which removes the tight coupling between a controller and a concrete repository and makes the controller testable with a fake implementation. The IoC container is the piece of infrastructure that performs the injection: services are registered once in Program.cs with a lifetime of transient, scoped or singleton, and the container then creates every controller and supplies its dependencies. Controllers themselves are created by inheriting Controller (or ControllerBase for a Web API), and their public action methods return an IActionResult such as View(), Json(), RedirectToAction() or NotFound() according to what the request needs.
Building and running .NET Core applications
0 · 5 marks
How do you build, run abd test .NET core applications? [5]
Make Unit 5 stick
Practice BIT351 with flashcards & quizzes