第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

使用 DI 訪問(wèn) Startup.cs 中的 NPGSQL

使用 DI 訪問(wèn) Startup.cs 中的 NPGSQL

C#
慕仙森 2023-05-13 16:21:26
使用 .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>


查看完整回答
反對(duì) 回復(fù) 2023-05-13
  • 1 回答
  • 0 關(guān)注
  • 143 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)