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:
- 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 (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.