Asp.net問題隨筆: An attempt was made to use the context while it is…nce members are not guaranteed to be thread safe
阿新 • • 發佈:2021-12-14
用.net 5在做Vue的webapi開發的時候,一個頁面調多個介面的時候就會返回這樣的紅色報錯:An attempt was made to use the context while it is…nce members are not guaranteed to be thread safe。
查看了一下執行緒;兩個Action使用的不一樣。
//檢視執行緒
Thread.GetCurrentProcessorId();
初步判斷是兩個介面的間隙時間太短,前一個還沒完成的情況下又來一個,兩個執行緒同時使用了EF Core的同一服務導致的不安全。
於是跟了下服務的生命週期,官方程式碼如下
namespaceMicrosoft.Extensions.DependencyInjection { // // 摘要: // Specifies the lifetime of a service in an Microsoft.Extensions.DependencyInjection.IServiceCollection. public enum ServiceLifetime { // // 摘要: // Specifies that a single instance of the service will be created.Singleton, // // 摘要: // Specifies that a new instance of the service will be created for each scope. // // 言論: // In ASP.NET Core applications a scope is created around each server request. Scoped, // // 摘要: // Specifies that a new instance of the service will be created every time it is// requested. Transient } }
解決方法是將之前Startup裡用的
ServiceLifetime.Scoped 換成 ServiceLifetime.Transient;每次請求時,都建立一個服務的新例項。這樣就不會衝突了。程式碼如下:
services.AddDbContext<MySqlDbContext>(options => options.UseMySql(connection).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking), ServiceLifetime.Transient);
services.AddTransient<IRepositoryBase, RepositoryBase>();