54

I need to setup a few dependencies (services) in the ConfigureServices method in an ASP.NET Core 1.0 web application.

The issue is that based on the new JSON configuration I need to setup a service or another.

I can't seem to actually read the settings in the ConfigureServices phase of the app lifetime:

public void ConfigureServices(IServiceCollection services)
{
    var section = Configuration.GetSection("MySettings"); // this does not actually hold the settings
    services.Configure<MySettingsClass>(section); // this is a setup instruction, I can't actually get a MySettingsClass instance with the settings
    // ...
    // set up services
    services.AddSingleton(typeof(ISomething), typeof(ConcreteSomething));
}

I would need to actually read that section and decide what to register for ISomething (maybe a different type than ConcreteSomething).

Pang
  • 9,564
  • 146
  • 81
  • 122
Andrei Rînea
  • 20,288
  • 17
  • 117
  • 166

6 Answers6

75

That is the way you can get the typed settings from appSettings.json right in ConfigureServices method:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MySettings>(Configuration.GetSection(nameof(MySettings)));
        services.AddSingleton(Configuration);

        // ...

        var settings = Configuration.GetSection(nameof(MySettings)).Get<MySettings>();
        int maxNumberOfSomething = settings.MaxNumberOfSomething;

        // ...
    }

    // ...
}
spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Dmitry Pavlov
  • 30,789
  • 8
  • 97
  • 121
17

Starting from ASP.NET Core 2.0 we do configuration setup in Program class when building WebHost instance. Example of such setup:

return new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .ConfigureAppConfiguration((builderContext, config) =>
    {
        IHostingEnvironment env = builderContext.HostingEnvironment;

        config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    })

Among others, this allows using configuration directly in Startup class, getting an instance of IConfiguration via constructor injection (thank you, built-in DI container):

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    ...
}
spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Set
  • 47,577
  • 22
  • 132
  • 150
  • yeah! worked for me. finally i can get my stuff from json entries to prepare my services :\ – AmiNadimi Feb 22 '18 at 21:23
  • 3
    How does this work when an ASP.NET Core 2.1 application is hosted under IIS? The `WebHostBuilder` won't be used, so what is in that `IConfiguration configuration` that's passed into `Startup`'s constructor? – Dai Jul 23 '18 at 03:15
5

You can access appsettings.json values by Configuration["ConfigSection:ConfigValue"])

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyContext>(o => 
            o.UseSqlServer(Configuration["AppSettings:SqlConn"]));
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System": "Information",
      "Microsoft": "Warning"
    }
  },
  "AppSettings": {
    "SqlConn": "Data Source=MyServer\\MyInstance;Initial Catalog=MyDb;User ID=sa;Password=password;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;"
  }
}

Dave ت Maher
  • 1,561
  • 14
  • 8
1

The appsettings.json file :

  "MyApp": {
    "Jwt": {
      "JwtSecretConfigKey": "jwtSecretConfigKey",
      "Issuer": "appIssuer",
      "Audience": "appAudience",
      "ExpireMinutes": 60
    }
  }

add a class to bind Jwt section of "MyApp" ...

   public class JwtConfig
    {
        public string JwtSecretConfigKey { get; set; }
        public string Issuer { get; set; }
        public string Audience { get; set; }
        public int ExpireMinutes { get; set; }
    }

In ConfigureServices method :

//reading config from appsettings.json
var jwtConfig = Configuration.GetSection("MyApp:Jwt").Get<JwtConfig>();

//using config data ....
services.AddJwt(new AddJwtOptions(jwtConfig.JwtSecretConfigKey, jwtConfig.Issuer, jwtConfig.Audience, jwtConfig.ExpireMinutes));

The code below is the same as above. it works as well...

var jwtConfig = Configuration.GetSection("MyApp").GetSection("Jwt").Get<JwtConfig>();

Hope this helps..

Namig Hajiyev
  • 1,117
  • 15
  • 16
1

Try next:

var settings = new MySettings();
Configuration.GetSection(nameof(MySettings)).Bind(settings);
Mardok
  • 624
  • 8
  • 18
1

This took me a horrifically long time but I got there in the end using IConfiguration.Bind().

I particularly wanted a flat configuration file rather than having to define a section.

Example appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "MyApiBaseUrl": "https://api.example.com",
  "MyApiKey": "example-api-key",
  "AllowedHosts": "*"
}

We need a helper class to bind to CustomApplicationConfiguration:

public class CustomApplicationConfiguration
{
    public string MyApiBaseUrl { get; set; }
    public string MyApiKey { get; set; }
}

Then define and bind inside ConfigureServices(IServiceCollection services):

public void ConfigureServices(IServiceCollection services)
{
    var settings = new ApplicationConfiguration();
    Configuration.Bind(settings);

    Console.WriteLine(settings.MyApiBaseUrl); // https://api.example.com
    Console.WriteLine(settings.MyApiKey); // example-api-key