Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 将数据库表加载为IOption<&燃气轮机;启动时_Entity Framework_.net Core_Configuration - Fatal编程技术网

Entity framework 将数据库表加载为IOption<&燃气轮机;启动时

Entity framework 将数据库表加载为IOption<&燃气轮机;启动时,entity-framework,.net-core,configuration,Entity Framework,.net Core,Configuration,.Net核心3.1应用程序。Startup.cs中的ConfigureServices设置EF Core 5 DbContext。我希望将其中一个“静态”表加载到内存中,并通过AddOptions使其可用,从而使该表可在整个应用程序中注入(廉价缓存)。与appsettings中的绑定相同,但使用EF核心数据库 我已经通过创建一个作用域并让DbContext服务运行一个初始化方法,在Main中为数据库“播种”。这种技术在本例中不起作用,因为我正在添加服务。当我仍在ConfigureServices

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

我已经通过创建一个作用域并让DbContext服务运行一个初始化方法,在Main中为数据库“播种”。这种技术在本例中不起作用,因为我正在添加服务。当我仍在ConfigureServices中时,是否有方法读取DbContext?一种在主机构建但未运行时添加服务的方法


你会怎么做?你不知道吗。我发布了这个问题,并不断地重新定义我的搜索词,挖掘和瞧

所以我创建了一个类

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();
            }
        }
    }
}
使用MyContexts;
使用MyModels;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Options;
使用System.Linq;
公共类LoadMySettings:IConfigureOptions
{
专用readonly IServiceScopeFactory\u serviceScopeFactory;
公共加载我的设置(IServiceScopeFactory服务ScopeFactory)
{
_serviceScopeFactory=serviceScopeFactory;
}
公共void配置(MySettings选项)
{
使用(var scope=\u serviceScopeFactory.CreateScope())
{
var provider=scope.ServiceProvider;
使用(var dbContext=provider.GetRequiredService())
{
options.MySettingsList=dbContext.MySettingsTable.ToList();
}
}
}
}
并将其嵌入到ConfigureServices中:

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

简单的解决方案是在启动时不将DI用于所需的任何DbContext;只需使用块在
中“新建一个”。当根据当前请求中的数据(例如多租户)配置DI DbContext时,也需要此模式。