На самом деле прочитайте AppSettings на этапе ConfigureServices в ASP.NET Core.

Мне нужно настроить несколько зависимостей (служб) в методе ConfigureServices в веб-приложении ASP.NET Core 1.0.

Проблема в том, что на основе новой конфигурации JSON мне нужно настроить ту или иную службу.

Кажется, я не могу прочитать настройки на этапе ConfigureServices жизненного цикла приложения:

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));
}

Мне нужно было бы на самом деле прочитать этот раздел и решить, что зарегистрировать для ISomething (возможно, другого типа, чем ConcreteSomething).


person Andrei Rînea    schedule 07.11.2016    source источник
comment
См. stackoverflow.com/q/40397648/5426333.   -  person adem caglin    schedule 07.11.2016
comment
@ademcaglin: Спасибо! Вот оно. Я проголосовал за то, чтобы закрыть свой вопрос как дубликат этого :)   -  person Andrei Rînea    schedule 08.11.2016
comment
Связанный ответ заключается в получении значений из файла конфигурации, а не из файла appsettings.json.   -  person im1dermike    schedule 24.03.2017
comment
Возможный дубликат раздела ASP.NET Core Configuration в Startup   -  person Cake or Death    schedule 28.11.2017


Ответы (4)


Таким образом, вы можете получить типизированные настройки из appSettings.json прямо в методе ConfigureServices:

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;

        // ...
    }

    // ...
}
person Dmitry Pavlov    schedule 16.05.2018

Начиная с ASP.NET Core 2.0, мы выполняем настройку конфигурации в классе Program при создании экземпляра WebHost. Пример такой установки:

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);
    })

Среди прочего, это позволяет использовать конфигурацию непосредственно в классе Startup, получить экземпляр IConfiguration через внедрение конструктора (спасибо, встроенный DI-контейнер):

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

    public IConfiguration Configuration { get; }

    ...
}
person Set    schedule 05.02.2018
comment
Да! работал на меня. наконец, я могу получить свои материалы из записей json, чтобы подготовить свои услуги: \ - person AmiNadimi; 23.02.2018
comment
Как это работает, когда приложение ASP.NET Core 2.1 размещается в IIS? WebHostBuilder использоваться не будет, так что же находится в этом IConfiguration configuration, переданном в конструктор Startup? - person Dai; 23.07.2018

Вы можете получить доступ к значениям appsettings.json 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;"
  }
}

person Dave ت Maher    schedule 15.08.2019
comment
Нет, Конфигурация объекта пришла как нулевая - person Bisneto; 10.03.2020

Файл appsettings.json:

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

добавьте класс для привязки раздела Jwt MyApp...

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

В методе ConfigureServices:

//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));

Код ниже такой же, как и выше. тоже работает...

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

Надеюсь это поможет..

person Namig Hajiyev    schedule 02.07.2020