出問題的代碼如下: public class DBBookChaptersService : IBookChaptersService { private readonly BooksContext _booksContext; public DBBookChaptersService(BooksC ...
出問題的代碼如下:
public class DBBookChaptersService : IBookChaptersService { private readonly BooksContext _booksContext; public DBBookChaptersService(BooksContext booksContext) { _booksContext = booksContext;} public async Task Add(BookChapter bookChapter) { await _booksContext.Chapters.AddAsync(bookChapter); await _booksContext.SaveChangesAsync(); //此處寫入資料庫時會拋出異常 } }
經分析查找原因如下:
通過依賴註入的上下文執行到SaveChangesAsync這個非同步方法時,會直接Dispose掉, 導致回調失敗.
解決辦法:
1. 使用同步方法SaveChanges().
此方法最簡單, 也可以新構造一個非同步方法將其包起來實現非同步調用.
2. 不用依賴註入的上下文, 而是臨時生成上下文, 具體步驟如下:
此方法並非完全不使用依賴註入, 只是捨棄依賴註入上下文,而使用依賴註入的DbContextOptions<T>來構造臨時上下文.
public class DBBookChaptersService : IBookChaptersService { private readonly BooksContext _booksContext; // 1. 採用依賴註入獲得DbContextOptions private readonly DbContextOptions<BooksContext> _options; public DBBookChaptersService(BooksContext booksContext, DbContextOptions<BooksContext> options) { _booksContext = booksContext; _options = options; } public async Task Add(BookChapter bookChapter) { // 2. 用optins生成臨時上下文, 執行非同步SaveChangesAsync() using (var context = new BooksContext(_options)) { await context.Chapters.AddAsync(bookChapter); await context.SaveChangesAsync(); }