Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can we inject the service dependency into the controller C# Asp.net Core?
ASP.NET Core uses a built-in Inversion of Control (IoC) container to inject dependencies into controllers and other services. This container, represented by the IServiceProvider implementation, supports constructor injection by default and manages application services throughout their lifecycle.
To use dependency injection in controllers, you must first register your services with the IoC container in the ConfigureServices method of the Startup class or Program.cs file.
Syntax
Following is the syntax for registering services in the IoC container −
services.AddSingleton<IInterface, Implementation>(); services.AddScoped<IInterface, Implementation>(); services.AddTransient<IInterface, Implementation>();
Following is the syntax for constructor injection in a controller −
public class HomeController : Controller {
private readonly IInterface _service;
public HomeController(IInterface service) {
_service = service;
}
}
Service Registration and Injection
First, create a service interface and its implementation −
using System;
public interface ILog {
void Info(string message);
}
public class MyConsoleLogger : ILog {
public void Info(string message) {
Console.WriteLine($"LOG: {message}");
}
}
Register the service in ConfigureServices method −
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton<ILog, MyConsoleLogger>();
}
}
Using Dependency Injection in Controllers
Once registered, the IoC container automatically injects the service into controller constructors −
using Microsoft.AspNetCore.Mvc;
using System;
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase {
private readonly ILog _logger;
public HomeController(ILog logger) {
_logger = logger;
}
[HttpGet]
public IActionResult Get() {
_logger.Info("HomeController Get method called");
return Ok("Hello from HomeController");
}
}
public class Program {
public static void Main(string[] args) {
var builder = WebApplication.CreateBuilder(args);
// Register services
builder.Services.AddControllers();
builder.Services.AddSingleton<ILog, MyConsoleLogger>();
var app = builder.Build();
app.MapControllers();
app.Run();
}
}
Service Lifetimes
ASP.NET Core supports three service lifetimes −
| Lifetime | Method | Description |
|---|---|---|
| Singleton | AddSingleton() | One instance for the entire application lifetime |
| Scoped | AddScoped() | One instance per request |
| Transient | AddTransient() | New instance every time it's requested |
Example with Different Lifetimes
using Microsoft.AspNetCore.Mvc;
using System;
public interface ICounter {
int GetNext();
}
public class Counter : ICounter {
private int _count = 0;
public int GetNext() {
return ++_count;
}
}
[ApiController]
[Route("[controller]")]
public class CounterController : ControllerBase {
private readonly ICounter _counter;
public CounterController(ICounter counter) {
_counter = counter;
}
[HttpGet]
public IActionResult Get() {
int count = _counter.GetNext();
return Ok($"Count: {count}");
}
}
public class Program {
public static void Main(string[] args) {
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Try changing to AddScoped or AddTransient to see different behavior
builder.Services.AddSingleton<ICounter, Counter>();
var app = builder.Build();
app.MapControllers();
app.Run();
}
}
The output when calling the endpoint multiple times (with Singleton lifetime) −
First call: Count: 1 Second call: Count: 2 Third call: Count: 3
Method Injection
Besides constructor injection, you can also use method injection with the [FromServices] attribute −
[HttpGet("method-injection")]
public IActionResult GetWithMethodInjection([FromServices] ILog logger) {
logger.Info("Method injection example");
return Ok("Method injection used");
}
Conclusion
ASP.NET Core's built-in IoC container enables clean dependency injection by registering services in ConfigureServices and automatically injecting them into controller constructors. This promotes loose coupling, testability, and better code organization through the Dependency Inversion Principle.
