C# 在IConfigureOptions中获取DatabaseContext实例
我已经按照从数据库中获取选项,但我有一个错误 System.InvalidOperationException:“ValueFactory试图访问此实例的Value属性。” 我不知道为什么会这样。错误是在C# 在IConfigureOptions中获取DatabaseContext实例,c#,entity-framework-core,asp.net-core-3.0,C#,Entity Framework Core,Asp.net Core 3.0,我已经按照从数据库中获取选项,但我有一个错误 System.InvalidOperationException:“ValueFactory试图访问此实例的Value属性。” 我不知道为什么会这样。错误是在OnModelCreating()方法中生成的,尤其是在base.OnModelCreating(modelBuilder)中我使用Identity和.NET Core 3 public void ConfigureServices(IServiceCollection serviceColle
OnModelCreating()方法中生成的,尤其是在base.OnModelCreating(modelBuilder)中代码>
我使用Identity和.NET Core 3
public void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.AddDbContext<DatabaseContext>(x =>
x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// some code here
serviceCollection.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddRoleStore<ApplicationRoleStore>()
.AddUserStore<ApplicationUserStore>()
.AddUserManager<ApplicationUserManager>()
.AddRoleManager<ApplicationRoleManager>()
.AddSignInManager<ApplicationSignInManager>()
.AddDefaultTokenProviders();
serviceCollection.AddSingleton<IConfigureOptions<IdentityOptions>, ConfigureIdentityOptions>();
}
public class ConfigureIdentityOptions : IConfigureOptions<IdentityOptions>
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public ConfigureIdentityOptions(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
public void Configure(IdentityOptions identityOptions)
{
using (var currentScope = _serviceScopeFactory.CreateScope())
{
using (var databaseContext = currentScope.ServiceProvider.GetRequiredService<DatabaseContext>())
{
var users = databaseContext.Users.ToList(); // ERROR HERE
}
}
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); // ERROR HERE
modelBuilder.HasDefaultSchema("Sample.API");
}
public void配置服务(IServiceCollection服务集合)
{
serviceCollection.AddDbContext(x=>
x、 使用SQLServer(Configuration.GetConnectionString(“DefaultConnection”));
//这里有一些代码
serviceCollection.AddIdentity您可以看到整个代码
错误屏幕截图
这是由循环依赖性引起的吗?您的上下文不需要IConfigureOptions。@johnny5 Thx!我有办法修复它并从数据库加载选项吗?谢谢!1.不要将配置存储在数据库中。或2.创建原始sql查询以获取信息。或3.创建一个虚拟上下文以获取信息n无配置,其唯一目的是仅在启动类中获得配置。对于johnny 5的第二个选项,您需要尝试SqlConnection
来创建原始sql查询,您无法从DatabaseContext
运行原始sql。感谢您的帮助。没有“更优雅”的选项是多么奇怪啊解决方案,可能是一个限制或错误。这是由循环依赖关系引起的,您的上下文不需要IConfigureOptions。@johnny5 Thx!我有办法修复它并从数据库加载选项吗?谢谢!1.不要将配置存储在数据库中。或2.创建原始sql查询以获取信息。或3.创建一个不接受任何配置的虚拟上下文,其唯一目的是仅在启动类中获取配置。对于johnny 5的第二个选项,您需要尝试SqlConnection
来创建原始sql查询,您无法从DatabaseContext
运行原始sql。感谢您的帮助。有我这样做真奇怪没有“更优雅”的解决方案,也许这是一个限制或缺陷。