【问题标题】:How can I take advantage of the DbContext Pooling out of ASP.NET Core LifeCycle?如何利用 ASP.NET Core LifeCycle 中的 DbContext 池?
【发布时间】:2019-03-31 04:50:37
【问题描述】:

我有一个对象是每组用户来管理内存中的并发更改。以固定速率,比如每六秒,我获取更改的当前状态并将其应用到数据库。重要的部分是有一个单独的线程需要 ASP.NET Core MVC 生命周期之外的 dbcontext 实例。这很困难,或者我不知道如何利用猥亵注入。

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

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

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 生命周期,而不改变其功能,即在我的用例中找到一种利用依赖注入的方法。
  5. *接受建议

【问题讨论】:

  • 很好,谢谢。微软营销可能......令人沮丧。看起来他们只是将其称为 ASP.NET 核心 MVC。 Overview of ASP.NET Core MVC

标签: c# asp.net-core entity-framework-core


【解决方案1】:

提出问题有助于我回答自己的问题或找到解决方案。以下所有内容均使用在请求之外运行的线程进行了测试。

原来我们可以通过 API 注入服务提供者来创建我们自己的实例!

ReadOnly IServiceProvider _ServiceProvider;

MySingulation(IServiceProvider serviceProvider)
{
    _ServiceProvider = serviceProvider;
}

一旦我们通过注入获得了 IServiceProvider 的句柄,我们就可以使用 MVC Core API 创建上下文实例

using(var serviceScope = _ServiceProvider.CreateScope())
{
    // Don't get confused -- Call GetService from the serviceScope and 
    // not directly from the member variable _ServiceProvider. 
    var context = serviceScope.ServiceProvider.GetService<YourAppDbContext>();

    // ...
    // Make use of the dbcontext
    // ...

}

现在,重要的是要记住我们一开始就在 Startup.cs 中使用了 MVC 核心池。

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddDbContextPool<YourAppDbContext>(options => {
        options.UseSqlServer(settings.Connection);
    });

    // Oh, it's important the singultion was created within Core's LifeCycle/API
    services.AddSingleton<MySingulation>();
    //...
}   

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 1970-01-01
    • 2018-12-31
    • 2017-11-12
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    相关资源
    最近更新 更多