在启动时将数据库 table 作为 IOption<> 加载

Load database table as IOption<> at startup

.Net Core 3.1 应用。 Startup.cs 中的 ConfigureServices 设置 EF Core 5 DbContext。我希望加载到内存中并通过 AddOptions 提供的“静态”table 之一,使 table 可注入整个应用程序(廉价的缓存)。与从 appsettings 绑定相同,但使用 EF Core 数据库。

我已经通过创建作用域并将 DbContext 服务获取到 运行 初始化方法来在 Main 中“播种”数据库。该技术在这种情况下不起作用,因为我正在添加服务。有没有办法在我还在 ConfigureServices 时读取 DbContext?一种在构建主机后添加服务但不添加服务的方法 运行?

会如何处理这个问题?

你不知道吗。我 post 这个问题并不断地重新构建我的搜索词并挖掘和瞧。

Using IConfigureOptions

所以我创建了一个class

using MyContexts;
using MyModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Linq;
public class LoadMySettings : IConfigureOptions<MySettings>
{
    private readonly IServiceScopeFactory _serviceScopeFactory;
    public LoadMySettings(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }
    public void Configure(MySettings options)
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            var provider = scope.ServiceProvider;
            using (var dbContext = provider.GetRequiredService<MyContext>())
            {
                options.MySettingsList = dbContext.MySettingsTable.ToList();
            }
        }
    }
}

并将其嵌入到 ConfigureServices 中:

services.AddSingleton>IConfigureOptions<MySettinmgs>, LoadMySettings>();