.net core 2.1 multiple DbContext for same database

asp.net-core-2.1 dbcontext entity-framework entity-framework-core


I am using .Net core 2.1 + EF Core to build WebApi. Based on this discussion: Entity Framework: One Database, Multiple DbContexts. Is this a bad idea? and the bounded context concept from DDD I want to create multiple DbContext for different functionalities in my app. There are several resources provided by Julie Lerman on PluralSight.com but non of those cover dependency injections in .net core. So far I did something like this:

var connectionString = Configuration.GetConnectionString("DatabaseName");

services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString, optionsBuilder =>
services.AddDbContext<ProductContext>(options =>
services.AddDbContext<CountryContext>(options =>

here DatabaseContext is a context used for EF Core migrations (does not actually query the data) and ProductContext and CountryContext are two of the contexts I use for my data manipulation. My questions are:

  • Is this a right way to do it? It feels a bit odd to re-use same connection string
  • It feels like I would be using 2 separete connections (and this will grow), could this cause some data access issues in the future, locks, concurency, etc?

UPDATE (2020-01-09)

I have been using this for more that a year now. Did not had any issues related to DB connection so far. Planning to use this this approach in future projects as well.

1/9/2020 8:45:20 AM

Popular Answer

The concept of having bounded contexts is fine, per se. It's based on the idea that the particular application shouldn't have access to things it doesn't need. Personally, I think it's a tad bit of overkill, but reasonable people can disagree on the issue.

However, what you have here, is simply wrong. If your application needs access to all these bounded contexts, it makes no sense to have them. Just feed it one context with all the access it needs. Yes, each context will have a separate connection, so yes, you will likely have multiple connections in play servicing requests. Again, this is why it makes no sense to divy out your contexts in this scenario.

If, however, you were to take a microservice architecture approach, where each microservice dealt with one discreet unit of functionality, and you wanted to be a purist about it, employing bounded contexts would make sense, but in a monolithic app, it does not.

9/11/2018 1:08:51 PM

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