Search code examples
identityserver4

Access ConfigurationDbContext outside startup


How can we access the same instance of ConfigurationDbContext outside the startup class after we configure it in the Startup.cs ? I want to create a repository with ConfigurationDbContext and want to use the same instance of ConfigurationDbContext as configured in startup.


Solution

  • As you could see in IdentityServer4.EntityFramework source code, ConfigurationDbContext is registered in built-in DI as Scoped (which actually means "per web request"). Moreover, it's also registered as implementation of IConfigurationDbContext interface.

    To get access to ConfigurationDbContext instance, just inject it in your services via DI:

    public MyService(IConfigurationDbContext context)
    {
    }
    
    public HomeController(ConfigurationDbContext context)
    {
    }