使用 .NET Core 2.1、NPGSQL、實體框架和 Linux。從 Startups.cs 的 Configure 函數中,我在依賴注入類中調用一個函數,該類又調用另一個依賴注入類,該類使用 Entity Framework + NPGSQL 訪問數據庫。配置服務: public void ConfigureServices(IServiceCollection services) { services.AddEntityFrameworkNpgsql() .AddDbContext<MMContext>(options => options.UseNpgsql($"Host='localhost'; Port=1234;Database='mydb';Username='test';Password='test'")) .BuildServiceProvider(); services.AddTransient<IMusicManager, MusicManager>(); services.AddTransient<IMusicRepo, MusicRepo>(); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }配置功能: public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvc(); using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { var mm = scope.ServiceProvider.GetRequiredService<IMusicManager>(); mm.DoSomeDBStartupStuff(); } }音樂管理器實現看起來像這樣: private readonly IMusicRepo _musicStoreRepo; public MusicManager(IMusicRepo musicStoreRep) { _musicStoreRepo = musicStoreRepo; } public void DoSomeDBStartupStuff() { _musicStoreRepo.InsertSampleStuff(); _musicStoreRepo.CheckThisAndCheckThat(); }音樂庫實現看起來像這樣: private readonly MMContext _context; public MusicRepo(MMContext context) { _context = context; } public void InsertSampleStuff() { _context.Music.AddAsync(new music("abc")); _context.Music.AddAsync(new music("123")); _context.SaveChangesAsync(); }MM上下文這是這樣實現的:public class MMContext : DbContext{ public MMContext(DbContextOptions<MMContext> options) : base(options) {} ... OnModelCreating etc...}
1 回答

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
注意函數中沒有等待異步調用void。
public void InsertSampleStuff()
{
_context.Music.AddAsync(new music("abc"));
_context.Music.AddAsync(new music("123"));
_context.SaveChangesAsync();
}
DbContext當您嘗試保存這些更改時,這可能會導致線程問題。
要么使函數異步并正確等待這些調用,要么使用同步 API
public void InsertSampleStuff() {
_context.Music.Add(new music("abc"));
_context.Music.Add(new music("123"));
_context.SaveChanges();
}
如果采用異步路線,則考慮將該設置代碼移至托管服務中并在那里適當地等待它
- 1 回答
- 0 關注
- 135 瀏覽
添加回答
舉報
0/150
提交
取消