使用 .NET Core 2.1、NPGSQL、實(shí)體框架和 Linux。從 Startups.cs 的 Configure 函數(shù)中,我在依賴注入類中調(diào)用一個(gè)函數(shù),該類又調(diào)用另一個(gè)依賴注入類,該類使用 Entity Framework + NPGSQL 訪問(wèn)數(shù)據(jù)庫(kù)。配置服務(wù): 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(); } }音樂(lè)管理器實(shí)現(xiàn)看起來(lái)像這樣: private readonly IMusicRepo _musicStoreRepo; public MusicManager(IMusicRepo musicStoreRep) { _musicStoreRepo = musicStoreRepo; } public void DoSomeDBStartupStuff() { _musicStoreRepo.InsertSampleStuff(); _musicStoreRepo.CheckThisAndCheckThat(); }音樂(lè)庫(kù)實(shí)現(xiàn)看起來(lái)像這樣: 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上下文這是這樣實(shí)現(xiàn)的:public class MMContext : DbContext{ public MMContext(DbContextOptions<MMContext> options) : base(options) {} ... OnModelCreating etc...}
1 回答

眼眸繁星
TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
注意函數(shù)中沒(méi)有等待異步調(diào)用void。
public void InsertSampleStuff()
{
_context.Music.AddAsync(new music("abc"));
_context.Music.AddAsync(new music("123"));
_context.SaveChangesAsync();
}
DbContext當(dāng)您嘗試保存這些更改時(shí),這可能會(huì)導(dǎo)致線程問(wèn)題。
要么使函數(shù)異步并正確等待這些調(diào)用,要么使用同步 API
public void InsertSampleStuff() {
_context.Music.Add(new music("abc"));
_context.Music.Add(new music("123"));
_context.SaveChanges();
}
如果采用異步路線,則考慮將該設(shè)置代碼移至托管服務(wù)中并在那里適當(dāng)?shù)氐却?/p>
- 1 回答
- 0 關(guān)注
- 143 瀏覽
添加回答
舉報(bào)
0/150
提交
取消