我有一個瞬態 EF DB 背景關系和一個瞬態服務。
我有一個控制器,它使用會話服務更新會話,然后使用會話服務查詢更新的會話。
但是,即使我使用瞬態,當我查詢更新的會話時,會話仍然是舊值,而不是更新的值。有人可以回答為什么嗎?
我的預期行為是,如果 DBContext 和 SessionService 是瞬態的,那么在我更新的會話之后獲取應該回傳一個新的更新值而不是舊值。因為 DBContext 應該在更新后被釋放。
啟動.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 - 使用 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()
{
}
uj5u.com熱心網友回復:
我認為對瞬態作用域的作業方式可能存在誤解。每次注入時都會實體化瞬態依賴項。在您的控制器中,瞬態和作用域依賴的行為方式相同。當另一個服務依賴于瞬態服務時,差異就出現了;該其他服務將接收瞬態服務的新實體。
因此,您的控制器將對整個請求使用相同的 SessionService(和相同的 EF 背景關系)。
要確保物體框架從資料庫中檢索最新值,請使用AsNoTracking查詢擴展(此處的檔案)。這將完全繞過 EF 快取并查詢底層資料庫。
此外,請確保等待更新會話資料后保存更改的 EF 呼叫。否則,您的 SELECT 陳述句可能會在應用 UPDATE 陳述句之前執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417748.html
標籤:
上一篇:如何在3D平面中獲得隨機點
