I am really confused about which to choose scoped vs transient.
If I inject the DbContext
as transient, I have the benefit that lets open many connections with SQL in one request.
For example
var clientCountTask = _clientRepo.CountAsync();
var orderCountTask = _orderRepo.CountAsnyc();
....
await Task.WhenAll(clientCountTask,orderCountTask,...);
Also, I can handle the transaction through a "Unit-of-work" class, but first I should inform you that the unit of work is injected as scoped.
For example
await _unitOfWork.OrderRepo.AddAsync(order);
await _unitOfWork.Cart.ClearAsync();
await _unitOfWork.SaveChangesAsnyc();
For scoped the benefits that I found over transient are:
- uses less memory
- handles the transaction without the need to the unit of work class
The disadvantages for scoped are:
- I can't open more the one request to the database
For example
var clientCountTask = _clientRepo.CountAsync();
var orderCountTask = _orderRepo.CountAsnyc();
....
await Task.WhenAll(clientCountTask,orderCountTask,...);
This throws an error:
A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
My questions are
What are the disadvantages of using transient to inject my
DbContext
?When I should use scoped over transient?
When I should use transient over scoped?