Get Db context inside data access layer

asp.net-core asp.net-mvc c# entity-framework-core

Question

I have some problems with EF-Core that I'm trying to figure out.
I use the startup code in the MVC Core application to initalize the db context.
This is my DB context:

public class AccountsDBContext : DbContext
{
    public AccountsDBContext(DbContextOptions<AccountsDBContext> options)
        :base(options)
    {

    }

    // ...

}

And startup code:

 public void ConfigureServices(IServiceCollection services)
 {
        // Inject the account db
        services.AddDbContext<AccountsDBContext>(options =>
           options.UseMySQL(Configuration.GetConnectionString("AccountsStore")));

        // ...

In all the exampes I see the DB Context is a delivered via the constructor to the controller (I assume by dependency injection) and from there on to other entities\ layers.

 [Route("api/[controller]")]
 public class AccountsController : Controller
 {
    private AccountsDBContext _db;

    public AccountsController(AccountsDBContext context)
    {
        this._db = context;
    }

However, I'm not very fond of the idea that the db context will be a member at the controller.
I really prefer to get a hold of the db context in the data access layer instead of getting it passed into the repositories classes.
Is there a way to get the context inside the data access layer? (There is no IServiceCollection, IApplicationBuilder, IServiceScopeFactory there as far as I know)

1
3
11/29/2016 10:46:59 AM

Popular Answer

Inject your repository/DAL implementation into the controller and have the DbContext injected into the repo constructor. The DI container will hook it all up as long as the appropriate classes are registered

0
9/26/2018 9:23:44 PM


Related Questions





Related

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