I have some questions and concerns about how to properly use the same DbContext connected to the same SQL Server DB, across multiple microservices.
My Problem
Currently, our software only uses a DbContext in one of our several microservices. This microservice, the Configuration
service, is primarily responsible for the business logic layer; it has many API routes that add, modify, or delete information from our Database. Now, there is a desire from stakeholders/upper management to persist some new information to our DB. However, this information is managed in a separate microservice, which I will refer to as the Metrics
microservice. Moving the management of metrics to a different microservice is out of scope for us, so we need to persist to the DB from the Metrics microservice.
Instantiating the DbContext
In our Configuration service, we use dependency injection to instantiate the DbContext
object across all controllers that need to access it for Database updates. First, we register our specific DbContext implementation, DbModelContext
, as a service in the IServiceCollection
using .AddDbContext(..)
. The following snippet is a simplified example to provide a better idea.
new ServiceInstanceListener(
serviceContext => new KestrelCommunicationListener(
serviceContext,
// Setting up ServiceInstanceListener
...
...
.ConfigureServices(
services => services
// Add Singletons ...
.AddDbContext<DbModelContext>(options => options.UseSqlServer(_efConnectionString, sqlServerOptions => sqlServerOptions.EnableRetryOnFailure())))
Now, we can inject our DbModelContext
object in any controller in the Configuration Service.
I would like to be able to follow the same pattern to inject a DbModelContext
object (pointing to the same SQL Server Database by using the same connection string) inside the controllers of the Metrics Microservice.
Questions and Concerns
I am very concerned about reading/writing to the same DB using two separate DBContext objects. To me, it seems like this is prone for issues with trying to read/write/delete records simultaneously, but I haven't been able to find any documentation about this.
If having two separate DbContext instances is an issue, is there a way to share the same instance across multiple microservices? I suppose I could have the Configuration Service call an API Endpoint of the Metrics microservice to send the DbContext to the Metrics microservice, but that doesn't seem ideal either.
I really am just curious if anyone has had a similar problem, and what approach they used to solve it.
Thank you!