Insert ASP.NET Core DbContext

I have ConfigurationDbContextone that I am trying to use. It has several options, DbContextOptionsand ConfigurationStoreOptions.

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

I tried to do 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
source share
3 answers

The implementation AddDbContext simply registers the context itself and its general dependencies in the DI. Instead of calling AddDbContextit, it is completely legal to manually register your DbContext:

services.AddTransient<FooContext>();

Alternatively, you can use the factory method to pass parameters (this is the answer to the question):

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

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

PS, , DbContextOptionsFactory DbContextOptions DbContext, .

+4

startup.cs.

: https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

: ASP.NET Core MVC Entity Framework

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>options.
       UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
+2

ef context - IDbContext

1- :

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

2- :

    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;
        }
    }
0

Source: https://habr.com/ru/post/1678910/


All Articles