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 ServiceB
that by means of DbContext
using different actions that they get another copy DbContext
.
The documentation reads as follows:
Transient
objects 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 ServiceA
and ServiceB
, it seems to me, is Transient
more 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())
{
var someEntity = new SomeEntity();
dbContext.SomeEntity.Add(someEntity);
dbContext.SaveChanges();
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 DbContext
not thread safe.
Should I use Transient
in this case? Why does the documentation suggest that I should use Scoped
?
- ?