Asp.net core has built in dependency injection. If you have a standard Asp.net core project you will find the method ConfigureServices in your startup.cs file which will look like the following:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
This is where you will register your services and how their lifecycle should be. Using AddTransient, AddScoped or AddSingleton of the services object in the above you can add dependencies which can be injected into your controllers. Below is an example:
Example using the WeatherForecast app
The usual WeatherForecast app that is used to demonstrate Asp.net has a WeatherForecastController with an endpoint like the following (I have inlined the Summary array for simplicity):
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
For this example we will move the logic within this GetWeatherForecast() method to another class and inject this into the controller instead. We will start by moving the above logic to a WeatherForecastService:
public class WeatherForecastService
{
public IEnumerable<WeatherForecast> GetWeatherForecast()
{
var Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
We then add this service as a dependency to our WeatherForecastController and invoke that instead of having the logic within the controller Get method:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly WeatherForecastService _weatherForecastService;
public WeatherForecastController(WeatherForecastService weatherForecastService)
{
_weatherForecastService = weatherForecastService;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return _weatherForecastService.GetWeatherForecast();
}
}
Finally we register this service in the ConfigureServices method in the startup.cs. We register it as a singleton as it has no state:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<WeatherForecastService>();
}
Now when firing up the WeatherForecast app we are greeted with the same old blob of json:
That is it!
I hope you enjoyed this very simple example of dependency injection in Asp.net core, let me know in the comments if you did!