MurabitoB
.Net Core Dependency Injection Scoped 注入到 Singleton

環境

  • .Net Core 3.1

問題

踩雷.

在專案中如果想對 Singleton 的 Service 中直接注入 Scoped 的 Service 的話,會拋出 Exception

下面範例取自黑暗執行緒

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: CRUDExample.Models.MemoryUsageMonitor': Cannot consume scoped service 'CRUDExample.Models.JournalDbContext' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.)'

原因是因為是在 Scoped 的生命週期結束後(一次 Request), Singleton 依然會存在,這並不符合設計的規範.

Entity Framework Identity 插入資料時自動獲得id

EntityFramework Identity 插入資料時自動獲得 id

環境

  • Visual Studio 2019
  • .Net Framework : 4.7.2
  • Entity Framework : 6.4.4
  • MySql.Data.EntityFramework: 8.0.18
  • DB : MariadDB

問題

在專案上有需要 MariadDB 的 Table 做資料維護,而 Database 是甲方爸爸開的,所以是必須以 Database First 的模式開發。

甲方爸爸的欄位皆以 int 做主鍵 id 並以 auto increment 做欄位的自動增值。

資料維護需要以 Ajax 的方式在新增之後馬上顯示在前端的頁面中,
被新增的資料有可能在同頁面中馬上被刪除,因此需要新增資料後要馬上取得該欄位的 id 並回傳給前端。

此外在插入資料的時候,並沒有直接指定值,而是由資料庫自動產生對應的 id,這就造成了無法知道生成的資料的 id。