I am working on microservices project in .NET Core which have a structure as given below project structure
In this solution, one is an API Gateway project, which is .NET Core project, and the rest projects under the folder 'microservices' are .NET Web API projects.
I have referenced this article: microservice-architecture-in-aspnet-core
In this article, they are working with different SQL Server databases for every microservice. I have only single database for all microservices.
Can anyone guide me in this scenario?
I would like to know where should I put my DbContext file and all the entities to use them in all microservices.
Thanks in advance.
Usually using shared database is considered anti-pattern in the microservices world. When you decide to use the microservices one of the goals is to achieve as loose coupling between components as possible, the shared database is usually an obstacle on the path to this. If there are serious reasons why you need it - maybe you should reconsider using microservices in the first place.
If you still want/need to use microservices with share database - then you should consider introducing logical split of the database into parts (maybe using schemas) which have no relations between each other and use multiple contexts (one per service).
If the approach is not feasible at this point for some reason (legacy database for example, though I still highly recommend to make it feasible) - then use the standard approach for n-tiered architectures - introduce the separate database project and store context there.
As Guru stron pointed out this may not be the best way to go about things, consider this.
Create a library project (maybe DAL (data access layer)) and reference that in all projects, declare your dbcontext/entities there.
We have the same setup. We even have multiple dbcontexts in one c# project.
You can then either keep migrations in a single executable project, or move migrations to the DAL project as well (either is fine afaik);
To use a seperate assembly see: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects?tabs=dotnet-core-cli
Ex.:
services.AddDbContextFactory<WebApiDbContext>(options =>
options.UseSqlServer(_defaultConnectionString, b =>
{
b.MigrationsAssembly(typeof(Initial).Assembly.GetName().Name);
...
Ìnitial
is an initial migration file.
A good read when using the ef cli tools is also; https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With