Reputation: 752
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:
I tried by keeping the file in a upper folder and then added the below settings in Program.cs
.
var sharedFolder = Path.Combine(env.ContentRootPath, "..\\..", "Shared");
config..AddJsonFile(Path.Combine(sharedFolder, "SharedSettings.json"), optional: false)
But this is not working as after publishing the project separately the folder will not be found.
Can anyone guide me how to achieve this and am I on the right track ?
Upvotes: 3
Views: 2034
Reputation: 1614
I had the same problem
I solved is by doing the following.
Create Class Library for all your shared dependencies
Create folder Called AppSettings in this class library. Store all your json configs in there
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