How do I manage the life time of a DbContext in MVC Core?

From the documentation

Entity Framework contexts must be added to the service container using a lifetime Scoped. This is automatically taken if you use helper methods as shown above. The vaults to be used from the Entity Framework should use the same lifetime.

I always thought that I should create a new Context for every single work that I have to handle. It makes me think, if I have ServiceA, and ServiceBthat by means of DbContextusing different actions that they get another copy DbContext.

The documentation reads as follows:

  • Transientobjects are always different; a new instance is provided to each controller and each service.

  • Scoped objects are the same in the request, but different in different requests

Returning to ServiceAand ServiceB, it seems to me, is Transientmore suitable.

I researched that Context should only be saved once per HttpRequest, but I really don't understand how this works.

If you look at one service:

using (var transaction = dbContext.Database.BeginTransaction())
{
    //Create some entity
    var someEntity = new SomeEntity();
    dbContext.SomeEntity.Add(someEntity);

    //Save in order to get the the id of the entity
    dbContext.SaveChanges();

    //Create related entity
    var relatedEntity = new RelatedEntity
    {
        SomeEntityId = someEntity.Id
    };
    dbContext.RelatedEntity.Add(relatedEntity)
    dbContext.SaveChanges();
    transaction.Commit();
}

Here we need to save the context in order to get the identifier of the object that is associated with the other that we just created.

At the same time, another service may update the same context. From what I read is DbContextnot thread safe.

Should I use Transientin this case? Why does the documentation suggest that I should use Scoped?

- ?

+4
2

, , , . concurrency , , .

, .. , , , . , , . , . , , : .

. , IServiceScopeFactory CreateScope. , . , , , .

, , , . :

using (var scope = _scopeFactory.CreateScope())
{
    var service = scope.ServiceProvider.GetService<BackgroundThreadService>();
    service.Run();
}

BackgroundThreadService .

+5

, concurrency , . , , concurrency , . , 2 (, ) HTTP- ().

Lifetimes - ( ). DI, - , . Transient , get object null, DI , . SingleInstance - , , .

. asp net , ( )

, , , , .

, , , https://github.com/aspnet/DependencyInjection

+2

Source: https://habr.com/ru/post/1686364/


All Articles