Search code examples
c#asp.net-coreasp.net-identityasp.net-core-2.1asp.net-core-identity

How to configure IdentityOptions outside ConfigureServices?


I want to configure ASP.NET Core Identity based on settings which resides in database rather than AppSetting.json or hard coded values. Consequently, I'am eager to call following line of code outside of method ConfigureServices(IServiceCollection services):

services.Configure<IdentityOptions>(x => x.Password.RequireDigit = true);

This way of calling will allow me to initialize DbContext before trying to configure Identity.

Currently I'm using services.BuildServiceProvider() in the ConfigureServices() to access database values. This style has a huge disadvantage for me: It puts an extra initialization on the application's DbContext which is dirty and slow. In the other hand, DbContext is instantiated two times instead of one.

If I was able to call services.Configure<IdentityOptions>() outside the ConfigureServices(), for example in the configure() method, I would be able to configure Identity options based on database values without initializing DbContext twice.

Again, my question is how to configure IdentityOptions outside ConfigureServices?

Any help is appreciated.


Solution

  • I ended up with injecting IOptions<IdentityOptions> options to the Configure() method as what follows:

        public virtual void Configure(IApplicationBuilder app, IOptions<IdentityOptions> options)
        {
          options.Value.Password.RequireDigit = true;
          //rest of configurations...
        }
    

    And it worked!

    Thanks to @Kirk for the link.