猿问

如何利用 ASP.NET Core LifeCycle 中的 DbContext 池?

我有一个对象是每组用户来管理内存中的并发更改。以固定的速度,比如每六秒,我获取更改的当前状态并将其应用于数据库。重要的部分是有一个单独的线程需要 ASP.NET Core MVC LifeCycle 之外的 dbcontext 实例。这使它变得困难,或者我不知道如何利用 indecency injection。


有没有办法在这个问题空间中利用 AddDbContextPool。似乎没有直接租用 AppDbContext 的方法,Microsoft 警告不要直接创建 AppDbContext,因为它的 API 可能会发生变化。据我所知,我没有办法将我的数据库上下文注入/租用到正在执行工作的线程中。


我正在使用 Reactive API 处理线程,我在其中创建了一个 Subjects 并使用了 Sample 管道,如下例所示:


UpdateSubject

    .Sample(TimeSpan.FromSeconds(6))

    .Subscribe(x => {


        // This is where I'd like to take 

        // advantage of the dbcontext pooling

        using(AppDbContext db = new AppDbContext){


            // ...

            // Iterate Over Changes

            // ...


            db.SaveChanges();

        }


   });

我目前的感知选项是。

  1. 什么都不做:架构已经在整合呼叫。

  2. 实施我自己的池并研究如何为每次使用重置上下文,

  3. 自己使用/实现 Microsoft 的内部类 DbContextPool 尽管有警告它严格用于内部使用并且 API 可能会更改

  4. 在我的用例中找到一种方法使其脱离 ASP.NET Core MVC 生命周期而不改变其功能,即 IE,找到一种利用依赖注入的方法。

  5. *接受建议


红糖糍粑
浏览 78回答 1
1回答

UYOU

问这个问题帮助我回答了我自己的问题,或者找到了解决方案。下面的所有内容都使用在请求之外运行的线程进行了测试。原来我们可以通过 API 注入服务提供者来创建我们自己的实例!ReadOnly IServiceProvider _ServiceProvider;MySingulation(IServiceProvider serviceProvider){&nbsp; &nbsp; _ServiceProvider = serviceProvider;}一旦我们通过注入获得了 IServiceProvider 的句柄,我们就可以使用 MVC 核心 API 来创建上下文实例using(var serviceScope = _ServiceProvider.CreateScope()){&nbsp; &nbsp; // Don't get confused -- Call GetService from the serviceScope and&nbsp;&nbsp; &nbsp; // not directly from the member variable _ServiceProvider.&nbsp;&nbsp; &nbsp; var context = serviceScope.ServiceProvider.GetService<YourAppDbContext>();&nbsp; &nbsp; // ...&nbsp; &nbsp; // Make use of the dbcontext&nbsp; &nbsp; // ...}现在,重要的是要记住我们首先在 Startup.cs 中使用了 MVC 核心池。public void ConfigureServices(IServiceCollection services){&nbsp; &nbsp; //...&nbsp; &nbsp; services.AddDbContextPool<YourAppDbContext>(options => {&nbsp; &nbsp; &nbsp; &nbsp; options.UseSqlServer(settings.Connection);&nbsp; &nbsp; });&nbsp; &nbsp; // Oh, it's important the singultion was created within Core's LifeCycle/API&nbsp; &nbsp; services.AddSingleton<MySingulation>();&nbsp; &nbsp; //...}&nbsp; &nbsp;
随时随地看视频慕课网APP
我要回答