Search code examples
c#sql-serverasp.net-coremicroservices

How to store Connection Strings in a central location for Microservices


I've a solution with 8 microservices. But we are using same databases across the 8 microservices. They all are designed with single responsibility in mind.

So far I tried 3 approaches.

APPROACH: 1

Setting connection strings in individual project's appsettings.json file and accessing it using IConfiguration (DI). But now if there is a change I need to manually change all 8 appsettings.json file

APPROACH: 2

Created a shared class library with const string connection strings in it and referencing it in all 8 projects. This seems good for me but during each deployment we had to recompile.

APPROACH: 3

Created a single JSON file on a central shared location and used a JSON parser to read every time I need to connect to database. This looks flexible for me at the cost of performance.

Is there any better alternative to define & use connection string across the 8 microservices without compromising flexibility and performance or with least impact?


Solution

  • Just because the individual Microservices today connect to the same DB, does not mean that they will in the future, and this should be managed via configuration of the ConnectionString.

    Therefore approach 2 is out.

    Approach 1 is fine. Yes you have to change it 8 times, but how often will this change? And if you do start using different DBs then it might only be once.

    Approach 3: Here I would suggest that you don't do this yourself, but instead use more standard approach via K8s/Helm charts.

    You can do this via Secrets stored on a volume. Or perhaps better, is via Helm Charts Values.yaml files.

    This article is a little dated (so syntax might have changed) but gives a good idea of how to do some of these.

    https://pascalnaber.wordpress.com/2017/11/29/handling-settings-and-environment-variables-of-your-net-core-2-application-hosted-in-a-docker-container-during-development-and-on-kubernetes-helm-to-the-resque/