A
A
Alexey2019-06-29 17:58:00
ASP.NET
Alexey, 2019-06-29 17:58:00

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

1 answer(s)
L
lil_toady, 2019-07-09
@lil_toady

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 question

Ask a Question

731 491 924 answers to any question