I have a ConfigurationDbContext that I am trying to use. It has multiple parameters, DbContextOptions and ConfigurationStoreOptions.

How can I add this DbContext to my services in ASP.NET Core?

I have attempted the following in my Startup.cs:


private ConfigurationDbContext BuildDbContext(string connString)
    var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();

    var options = builder.Options;

    return new ConfigurationDbContext(options, new ConfigurationStoreOptions());
6/11/2017 2:04:55 PM

Accepted Answer

AddDbContext implementation just registers the context itself and its common dependencies in DI. Instead of AddDbContext call, it's perfectly legal to manually register your DbContext:


Moreover, you could use a factory method to pass parameters (this is answering the question):

services.AddTransient<FooContext>(provider =>
    //resolve another classes from DI
    var anyOtherClass = provider.GetService<AnyOtherClass>();

    //pass any parameters
    return new FooContext(foo, bar);

P.S., In general, you don't have to register DbContextOptionsFactory and default DbContextOptions to resolve DbContext itself, but it could be necessary in specific cases.

1/29/2019 4:20:23 PM

Popular Answer

You can use this in startup.cs.

Detail information :

Detail Example : Getting started with ASP.NET Core MVC and Entity Framework Core

public void ConfigureServices(IServiceCollection services)
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>options.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow