5 Dependency Injection And Application Configuration

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.

Dependency Injection and Application Configuration: notes

Dependency injection principles

A dependency is an object that a class needs to do its work. Dependency Injection (DI) is a design pattern where the class does not create its dependencies. They are given (injected) to it from outside, usually through the constructor.

Without DI, the class is tied to one concrete type:

public class OrderService
{
    private readonly EmailSender _sender = new EmailSender();   // tight coupling
}

With DI, the class depends on an interface:

public interface IMessageSender { void Send(string to, string text); }

public class EmailSender : IMessageSender
{
    public void Send(string to, string text) => Console.WriteLine($"Email to {to}: {text}");
}

public class OrderService
{
    private readonly IMessageSender _sender;
    public OrderService(IMessageSender sender) { _sender = sender; }   // injected
    public void Place(string user) => _sender.Send(user, "Order placed");
}

Principles behind DI:

  • Dependency Inversion: depend on abstractions (interfaces), not on concrete classes.
  • Inversion of control: the framework, not your code, creates and supplies objects.
  • Loose coupling: a class can use any implementation of the interface.

Benefits: easier unit testing with fake objects, simpler changes, and clearer code. Types of injection are constructor injection (most common), property injection and method injection.

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 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

TypeDescription
Constructor InjectionDependencies passed through the constructor
Property InjectionDependencies set through public properties
Method InjectionDependencies 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

LifetimeMethodDescription
TransientAddTransient<>()New instance every time it is requested
ScopedAddScoped<>()One instance per HTTP request
SingletonAddSingleton<>()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

  1. The class name must end with the suffix Controller (e.g., HomeController)
  2. It must inherit from the Controller base class (or ControllerBase for APIs)
  3. It must be placed in the Controllers folder (by convention)
  4. 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 TypeMethodDescription
ViewResultView()Returns an HTML view
RedirectResultRedirect()Redirects to a URL
JsonResultJson()Returns JSON data
ContentResultContent()Returns plain text
NotFoundResultNotFound()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.

Open this answer on its own page →

Building and running .NET Core applications

0 · 5 marks

How do you build, run abd test .NET core applications? [5]

Note: Reference notes were not available for this topic. The following answer is based on standard .NET Core documentation and practices, which align with the TU BSc CSIT curriculum. --- The dotnet build command compiles the application and its dependencies. - This compiles the source code into I...

Open this answer on its own page →