使用DI在startup.c中访问NPGSQL



使用.net core 2.1,npgsql,实体框架和linux。

从startups.cs的配置函数中,我正在调用依赖项注入依赖项中的函数,该类依次调用另一个依赖项注入依赖项,该类使用实体框架 NPGSQL访问DB。

配置服务:

    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();
        }
    }

imusicmanager

实现如下:

    private readonly IMusicRepo _musicStoreRepo;
    public MusicManager(IMusicRepo musicStoreRep)
    {
        _musicStoreRepo = musicStoreRepo;
    }
    public void DoSomeDBStartupStuff()
    {
        _musicStoreRepo.InsertSampleStuff();
        _musicStoreRepo.CheckThisAndCheckThat();
    }

imusicrepo

实现如下:

    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();
    }

mmcontext

这是这样实现的:

public class MMContext : DbContext
{
    public MMContext(DbContextOptions<MMContext> options) : base(options) {}
    ... OnModelCreating etc...
}

我会发射此例外:

应用程序启动异常:system.invalidoperationException: reset((在连接器上调用,并在状态执行状态 npgsql.npgsqlconnector.reset((at at at at NPGSQL.ConnectorPool.Release(NPGSQLConnector Connector(at npgsql.npgsqlconnection.close(boolean wasbroken(at npgsql.npgsqlconnection.dispose(布尔处置( system.componentmodel.component.dispose((at Microsoft.entityFrameWorkcore.storage.RelationalConnection.dispose(( 在 microsoft.extensions.ependentiondive.servicelookup.serviceproviderenginescope.dispose(( 在Microsoft.entityframeworkcore.dbcontext.dispose((at microsoft.extensions.ependentiondive.servicelookup.serviceproviderenginescope.dispose(( 在mm.startup.configure(iApplicationBuilder应用程序,iHostingenvironment( env(在 startup.cs:第122行 ---堆叠跟踪的结尾从以前的位置抛出了例外的位置--- microsoft.aspnetcore.hosting.conventionbasedstartup.configure(iapplicationBuilder app(at Microsoft.aspnetcore.hostfilteringstartupfilter。 app(at microsoft.aspnetcore.hosting.internal.autorequestservicesstartupfilter。 建造者( microsoft.aspnetcore.hosting.internal.webhost.buildapplication((

我不确定是什么原因引起了问题。可能是我使用依赖注入和使用范围的方式的方式?帮助赞赏。

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();
}

如果采用异步路线,请考虑将该设置代码移至托管服务中,并在此处正确等待

在ASP.NET Core中使用托管服务的参考参考背景任务