Introduction
When ASP.NET Core receives any request, it uses dependency injection container to resolve the required services & process request. When a webhost is built, framework services are registered with dependency injection container, for example: logging, routing, environment dependencies, configuration etc. When ASP.NET Core receives any request which needs framework component like controllers, the framework component is activated along with its dependencies.
Kestrol, the ASP.NET Core web server passes each request to suitable middleware; for example; HTTP requests are passed to MVC Middleware which chooses suitable controller to process request.

The controllers are not registered directly in dependency injection container but during the activation process of framework component, controller instance is resolvable in dependency injection. In simple words, services are registered with container at start-up and resolved from container at runtime - when they are required.
When registering any service with container, it is important to consider carefully the lifetime of service because chosen lifetime affects the reuse of service instances. Dependency injection container manages all instances of services it creates. Once the lifetime is passed, this service is disposed or released for garbage collection. Extension methods are used to define lifetime using IServiceCollection when registering the service. There are three type of service lifetimes: Transient , Singleton & Scoped
Example Scenario
With the help of an example, we will identify which service is suitable in which conditions. In our example, we have one Lucky Draw application that selects a lucky winner through a drawing. Suppose, a lucky winner is shown two screens in a company's own offices and also sent to agents who sell tickets as resellers. We need consistent data, the same one winner should be shown to all customers in a home office screen as well as the agent's (resellers) screens.
I have used a simple API application with many in-memory contestants. The constructor chooses one random contestant as winner which is returned as string when GetWinner method is called.
- public class LuckyDrawService
- {
- private readonly string[] Contestants = { "A100","B200","C300","D400","E500","F600","G700","H800", "I900", "J1000", "K1100", "L1200", "M1300", "N1400", "O1500", "P1600", "Q1700",
- "R1800", "S1900", "T2000", "U2100" };
- private readonly string lucky;
- public LuckyDrawService()
- {
- lucky = Contestants[new Random().Next(0,20)];
- }
- public string GetWinner() => lucky;
- }
We have custom middleware which utilizes LuckyDrawService service when handles each request, it gets a winner from service and adds to the message variable.
- public class AgentMiddleware
- {
- private readonly RequestDelegate _broadcast;
- public AgentMiddleware(RequestDelegate broadcast)
- {
- _broadcast = broadcast;
- }
- public async Task InvokeAsync(HttpContext request, LuckyDrawService luckyDrawService)
- {
- string message = $"Broadcast to Agents Screen: Winner is {luckyDrawService.GetWinner()}";
- request.Items.Add("AgentWinner", message);
- // Call the next delegate/middleware in the pipeline
- await _broadcast(request);
- }
Also, I have injected LuckyDrawService in HomeController contrtoller as well.







Adhi VenkateshPosted Oct 29, 2020, 9:20 AM
Hi Your explanations is nice but i have tried the same code but it is not working , hope that you some were missed the code for home screen , by this code giving null execption error ==> public IActionResult Index() { string message = $"Broadcast to Company Home Screen: Winner is {_luckyDrawService.GetWinner()}"; var screen = new List<string> { HttpContext.Items["AgentWinner"].ToString(), message }; return Ok(screen); } At same time for agent and home result is not coming same time only one is working to get HOME we need to hard code the value if we do the actual explanations for scope,transient will fail but singlton is good as per this code, you can check and revert with full code please.
Marko RadivojevicPosted Apr 11, 2020, 12:40 PM
Interesting, great. Thanks!
Rushi MehtaPosted Apr 3, 2020, 2:18 AM
Nice Article