簡體   English   中英

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

[英]How can I take advantage of the DbContext Pooling out of ASP.NET Core LifeCycle?

我有一個對象是每組用戶來管理內存中的並發更改。 以固定速率,比如每六秒,我獲取更改的當前狀態並將其應用到數據庫。 重要的部分是有一個單獨的線程需要一個位於 ASP.NET Core MVC LifeCycle 之外的 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 生命周期而不改變其功能,IE,找到一種在我的用例中利用依賴項注入的方法。
  5. *對建議持開放態度

問這個問題幫助我回答了我自己的問題,或者找到了解決方案。 下面的所有內容都使用在請求之外運行的線程進行了測試。

原來我們可以通過 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>();
    //...
}   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM