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 => optionsBuilder.MigrationsAssembly("Database.Migrations"))); services.AddDbContext<ProductContext>(options => options.UseSqlServer(connectionString)); services.AddDbContext<CountryContext>(options => options.UseSqlServer(connectionString));
DatabaseContext is a context used for EF Core migrations (does not actually query the data) and
CountryContext are two of the contexts I use for my data manipulation. My questions are:
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.
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.