13

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:

ConfigureServices
....
services.AddDbContext<ConfigurationDbContext>(BuildDbContext(connString));
....


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

    var options = builder.Options;

    return new ConfigurationDbContext(options, new ConfigurationStoreOptions());
}
3
  • do you use mssql server Commented Jun 9, 2017 at 22:03
  • yes. But, to construct the dbcontext, I require to pass another parameter to it. Commented Jun 9, 2017 at 22:05
  • i have also added example link Commented Jun 9, 2017 at 22:07

6 Answers 6

22

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:

services.AddTransient<FooContext>();

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It looks like AddDbContextPool also does the same
@Simon_Weaver thanks, I've updated the link. DbContextPool is something added in Core 2.0 I guess.
What would it look like for a generic context using a repository pattern?
5

You can use this in startup.cs.

Detail information : https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

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.
       UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

Comments

4

In order to register DbContext as a service in IServiceCollection you have two options:(we assume that you are going to connect to a SQL Server database)

Using AddDbContext<>

services.AddDbContext<YourDbContext>(o=>o.UseSqlServer(Your Connection String));

Using AddDbContextPool<>

services.AddDbContextPool<YourDbContext>(o=>o.UseSqlServer(Your Connection String));

as you might see these two are in terms of writing have similarities, but in fact they have some fundamental differences in terms of concepts. @GabrielLuci has a nice response about the differences between these two: https://stackoverflow.com/a/48444206/1666800

Also note that you can store your connection string inside the appsettings.json file and simply read it using: Configuration.GetConnectionString("DefaultConnection") inside the ConfigureServices method in Startup.cs file.

4 Comments

I have a question. If I add dbcontext in StartUp.cs, do I have to use AddSingleton or 'AddScoped` or AddTransient etc?
@Hello starting with .NET core 2.0 by using AddDbContextPool you do not need to use AddTransient or AddSingleton or AddScoped methods. Read these for more info: stackoverflow.com/a/44484724/1666800 , stackoverflow.com/questions/48443567/…
Thanks for your kindly reply, I don't use AddDbContextPool. I just use AddDbContext. Because I followed an example at here, it doesn't use this kind of things, I don't understand it.
@Hello nice. you can read more about these two function here: learn.microsoft.com/en-us/dotnet/api/… , learn.microsoft.com/en-us/dotnet/api/…
1

Try this for inject your ef context - context inheritance from IDbContext

1-Add your context to service:

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<NopaDbContext>(
                        options => options
                        .UseLazyLoadingProxies()
                        .UseSqlServer(Configuration.GetConnectionString("NopaDbContext")),ServiceLifetime.Scoped);}

2-Inject your context:

    private readonly IDbContext _context;

    public EfRepository(NopaDbContext context)
    {
        this._context = context;
    }

    protected virtual DbSet<TEntity> Entities
    {
        get
        {
            if (_entities == null)
                _entities = _context.Set<TEntity>();

            return _entities;
        }
    }

Comments

0

You can put all your parameters of db context in a class AppDbContextParams and register a factory to create that object for appdbcontext:

services.AddScoped(sp =>
            {
                var currentUser = sp.GetService<IHttpContextAccessor>()?.HttpContext?.User?.Identity?.Name;
                return new AppDbContextParams { GetCurrentUsernameCallback = () => currentUser ?? "n/a" };
            });

Comments

0

EF Core 6 / .NET 6 has some changes to make it easier (and supported) to register DbContext and DbContextPool at the same time for different usages.

https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-6.0/whatsnew#dbcontext-factory-improvements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.