Tufan Chand
Tufan Chand

Reputation: 752

Sharing configuration file among the projects in asp.net core

I have a solution in asp.net core and multiple API projects are present inside and that is a kind of micro services architecture. My solution structure looks like below.

ABC.API
DEF.API
GHI.API and so on....

I also have one more class library project that is having some common functionalities and can be used by all above API projects.

And I want to keep the connection string inside the class library project using json file or config file because all of the above are connecting to same database and i don't want to repeat those in all the projects.

Problem:

Can anyone guide me how to achieve this and am I on the right track ?

Upvotes: 3

Views: 2034

Answers (1)

cl0ud
cl0ud

Reputation: 1614

I had the same problem

I solved is by doing the following.

  1. Create Class Library for all your shared dependencies

  2. Create folder Called AppSettings in this class library. Store all your json configs in there

  3. I then created a static helper class in this class library called JsonConfiguration.cs See code

     public static class JsonConfiguration
    {
    
    public static IConfiguration ConfigurationContainer { get; private set; }
    
    public static IConfiguration CreateConfigurationContainer()
    {
        var environment = string.Empty;
        try
        {
            environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            _logger.Debug($"Found environment variable : {environment}");
            if (string.IsNullOrWhiteSpace(environment))
            {
                _logger.Debug($"Setting up Production appsettings.");
                //WE ARE IN PROD !!
                return ConfigurationContainer = new ConfigurationBuilder()
                    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                    .AddJsonFile($"bin/AppSettings/appsettings.json").Build();
            }
    
            _logger.Debug($"Setting up {environment} appsettings.");
            return ConfigurationContainer = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile($"bin/AppSettings/appsettings-{environment}.json").Build();
        }
        catch (Exception ex)
        {
            _logger.Fatal(ex, "{message} {environment}", "Failed Setting up Application Config.", environment);
            throw;
        }
    }
    

    }

Make sure your json files are marked as "Copy to output directory" to copy always.

You could then register the IConfiguration in the app that needs it and call JsonConfiguration.CreateConfigurationContainer(), I would probably map your connection strings to a a concrete model class and inject where needed. Hope this was enough to get you going.

Upvotes: 3

Related Questions