locked
Get DatabaseContext instance inside IConfigureOptions RRS feed

  • Question

  • User2035557611 posted

    Hi, I followed this tutorial (https://andrewlock.net/access-services-inside-options-and-startup-using-configureoptions/) to get the options from the database but I am having an error (System.InvalidOperationException: 'ValueFactory attempted to access the Value property of this instance.') I don't know why it happens. The error is generated within the "OnModelCreating ()" method, particularly in the "base.OnModelCreating (modelBuilder);". I use Identity.

    public void ConfigureServices(IServiceCollection serviceCollection)
    {
    
    	serviceCollection.AddDbContext<DatabaseContext>(x =>
    		x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    	
    	...
    	...
    	...
    	
    	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");
            }

    Code

    https://bitbucket.org/avechuche/.net-core-3-sample.api/src/master/

    Error

    Wednesday, November 6, 2019 6:02 PM

All replies

  • User1634355159 posted

    Hi avechuche,

    From this issue in github, show this question was fixed in the latest daily builds and will be included in preview 9.Hope it will help you.

    Best Regards,

    Lewis

    Thursday, November 7, 2019 10:05 AM
  • User2035557611 posted

    Hi Lewis. I'm not sure it's the same problem, I'm also using .NET Core 3 Final

    Thursday, November 7, 2019 12:38 PM