Reputation: 1634
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));
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:
UPDATE (2022-11-11)
I have been using this for few years now. Did not had any issues related to DB connection so far. Planning to use this this approach in future projects as well.
Upvotes: 2
Views: 6462
Reputation: 31
Just do it for each context:
services.AddScoped<YourContext>(s =>
{
var builder = new
DbContextOptionsBuilder().UseSqlServer("ConnectionString");
return new YourContext(builder.Options);
});
Upvotes: 0
Reputation: 239460
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.
Upvotes: 2