2

Hi I'm trying to write environment specific configuration for specflow test and I'm a little bit confused.

I know that in .net Core i have Environment variables and in web app i can just write this:

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

But how to use this in the library class project? My Solution is divided into a main project (class library) with specflow cases, and project that will handle the connection with DB. The connection strings have to change depending on the environment. I wanted to create appsettings.{env}.Json for each, but how can I assign appsetting file depending on env if I don't have startup class?

Tomasz Kaniewski
  • 1,065
  • 8
  • 16
  • Simple: You don't use Configuration/ConfigurationBuilder in class libraries. Configurations are to be set up by the application, not by the library. From the configuration builder, you bind to `IOption` (via `services.Configure(...)`) and inject these in your service classes – Tseng Jan 25 '19 at 08:53
  • As for Connectionstrings, you configure these always in the application startup (`.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"))`). Your library has to know nothing on where and how the connection strings are stored, this way you can easily solve naming conflicts (what would you do if your two libraries use "MyConnectionString" key, but have different providers or physical databases in the background? On application level its always up to the app creator how to name the connection string names and which one to pic for which use case – Tseng Jan 25 '19 at 08:55
  • This whole project is for testing the API, there is no "running application", just tests. My main project is Library Class where i run this specflow tests, and its have reference to Db projects with models etc. – Tomasz Kaniewski Jan 25 '19 at 09:04
  • Then your library design is flawed :P Your library classes should only take `IOptions`, `T` (if you don't want reference to `Microsoft.Extensions.Options`) and primitives (string, integer, etc). Refactor your library to only use these, then integration tests are no issue. As with DI/IoC you do it on the composition root (this may differ between project types, for unit tests the composition root would be the fixture or the setup/initialization method equivalents) – Tseng Jan 25 '19 at 09:08
  • I tried solutions from [here](https://stackoverflow.com/questions/39573571/net-core-console-application-how-to-configure-appsettings-per-environment) but they do not work. The tests proj. is unrelated to ASP.NET. – JohnTube May 28 '19 at 11:50

0 Answers0