EF Core Transient DBContext get old value

I have a transient EF DB context & a transient service.

I have a controller with an action using session service to update the session, and then use session service to query back the updated session.

However, even I use transient, when I query back the updated session, the session is still the old value but not the updated one. Can someone answer why?

My expected behavior is if DBContext & SessionService are transient, get after my updated session should return a new updated value instead of old value. Because DBContext should be disposed after the update.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    string connectionString = Configuration.GetConnectionString("ASPState");
    services.AddDbContext<ASPStateContext>(options =>
        options.UseSqlServer(connectionString, builder=> {
            builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
        }),ServiceLifetime.Transient);
    services.AddTransient<ISessionService, SessionService>();
    services.AddControllers();
}

SessionService.cs - using DI

private ASPStateContext aspStateContext;
public SessionService(ASPStateContext dbContext)
{
    aspStateContext = dbContext;
}

public async Task<IActionResult> UpdateSession(string id) {
    await this.sessionService.UpdateSession(id);
    var session = this.sessionService.GetSession(id); // return the value before update
}

ASPStateContext.cs

public partial class ASPStateContext : DbContext
{
    public ASPStateContext()
    {
    }

Solution 1:

I think there may be a misunderstanding about how the Transient scope works. A transient dependency is instantiated every time it is injected. Within your controller, a transient and a scoped dependency behave the same way. The difference emerges when another service depends on the transient service; that other service will receive a new instance of the transient service.

Therefore, your controller will use the same SessionService (and the same EF context) for an entire request.

To ensure that Entity Framework is retrieving the latest value from the database, use the AsNoTracking query extension (documentation here). This will completely bypass EF caching and query the underlying database.

Also, make sure that your EF call to save changes after updating the session data is awaited. Otherwise, your SELECT statement may execute before the UPDATE statement is applied.