ASP.NET Core DbContext injection

2020-08-15 10:27发布

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());
}

5条回答
叼着烟拽天下
2楼-- · 2020-08-15 10:59

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.

查看更多
小情绪 Triste *
3楼-- · 2020-08-15 11:18

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" };
            });
查看更多
戒情不戒烟
4楼-- · 2020-08-15 11:19

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.

查看更多
地球回转人心会变
5楼-- · 2020-08-15 11:22

You can use this in startup.cs.

Detail information : https://docs.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")));
}
查看更多
淡お忘
6楼-- · 2020-08-15 11:23

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;
        }
    }
查看更多
登录 后发表回答