Answer the question
In order to leave comments, you need to log in
What is the purpose of the CreateScope method, what advantages does it provide?
For example in this code
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<CatalogContext>();
CatalogSeed.SeedAsync(context).Wait();
}
catch (System.Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occured while seeding the database");
}
}
}
Answer the question
In order to leave comments, you need to log in
There are three types of lifetime of objects in the DI container (at least from Microsoft, which is considered here):
- Singleton - The object is created only once for the lifetime of the program, respectively, all who requested it will receive the same entity;
- Scoped - The object is created only once within the scope, and this entity will be passed to everyone who requested it within this scope, and then deleted (and Dispose is called if the IDisposable interface is implemented);
- Transient - An object is created on each request, that is, DI will always slip a new entity;
This is a mechanism for isolating and limiting the lifetime of an object. If we consider ASP.NET, then each request to the server is processed in its scope.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question