Reputation: 1175
Before reporting this question as duplicate, this SO Question covers the use of Transient, Scoped, and Singleton, but the answers and discussion target meanings mainly within the context of configuring a WebHost, but my question is relevant to the meaning of these types of services within the context of a (non-web) host, specifically confusion on Scoped Services.
Let's start with the code below:
In Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
I can wrap my head around what Transient and Singleton mean in the non-web host context.
But everywhere I read, a Scoped Service in the context of http requests would mean that a new instance is created for each (http?) request. The docs and other discussion is usually geared toward behavior when dealing with a web host, so I am in need of clarification...
What then, is the meaning of Scoped
within the context of configuring IServiceCollection
on a Default (non-web) HostBuilder?
Host.CreateDefaultBuilder(args)..ConfigureServices((hostContext, services) =>
{
services.AddHostedService<ConsumeScopedServiceHostedService>();
services.AddScoped<IScopedProcessingService, ScopedProcessingService>();
});
Also, see here for a practical example.
The closest understanding I came to is "Scoped lifetime services are created once per request (again, not http-request, but request for the service) within the scope. It is equivalent to a singleton in the current scope." ... meaning that if you AddScoped
when configuring services on the DefaultBuilder
(non-web host), when requested from that same scope, a new, completely separate instance of the service will be generated? Is this ballpark correct?
If I am way off here, I apologize. Thank you for your time.
Upvotes: 5
Views: 1107
Reputation: 5109
Yes, in a web host, a lifetime scope is created for the request.
In a console app, windows service, or any type of app, including a web hosted app, you can create a lifetime scope whenever you feel it is needed.
For example you might create a windows service that processes something on a schedule. It might make sense to create a lifetime scope each time the scheduled job is run. Now all components resolved in that scope that are registered as scoped will logically be scoped to it. This will keep your instances separate per run and they will be disposed along with the scope.
This could be useful if you have several different types of task that run independently and asynchronously. This way any component dependencies they have will be scoped properly.
Upvotes: 4