I have a multi layer application in which I have different projects for different purposes.

So lets simplify it and say I have:
- DataAccessLayer
- BusinessLogicLayer
- WebAPI Layer

With a simple hierarchy: Web references Logic references DAL

My DAL wants to know a connection string, of course different by envoriment (e.g. Dev / Test / Live Stage).

1) Where to store the connection strings? Store them in the DAL Project, because it is self organized and wants care about it's own things ("a database layer should know his connections") Or should I store them in the web project because it is the leading start project for my application?

2) What is the best strategy to load different json-configs (web) or application configs (class lib DAL) by envoriment in DotNet Core?

1 Answers

-1
user3280042 On

you appsettings files appsettings.dev.json may look like below

{
  "SampleObj": {
    "AnyPropName" :  "testProp" 
  } ,
  "ConnectionStrings": {
    "Test": "CONNECTION-STRING"
  }
}

some class

public class LocalAppSettings
    {
        public string ConnectionString { get; set; }

        public string AnyPropName { get; set; }
    }

startup.cs

 public IConfigurationRoot Configuration { get; set; } 

    public Startup(IHostingEnvironment env)
        {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

                //EnvironmentName = env.EnvironmentName;

                Configuration = builder.Build();
            }

    public void ConfigureServices(IServiceCollection services)
    {
         var settings = new LocalAppSettings
         {
              ConnectionString = Configuration.GetConnectionString("Test"),
              AnyPropName = Configuration.GetSection("SampleObj:AnyPropName").Value,
          };

    services.AddSingleton<LocalAppSettings>(settings)

    }

now as it is DI use this in class constructor in other projects

launchSettings.json looks like

"profiles": {
    "IIS Express": {
      "commandName": "Executable",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Local": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:4999"
    },
    "Development": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "dev"
      },
      "applicationUrl": "http://localhost:4999"
    }
  }

and if you plan to publish to azure dont forget to set ASPNETCORE_ENVIRONMENT in appsettings of app service