Actually read AppSettings in ConfigureServices phase in ASP.NET Core

前端 未结 4 1274
刺人心
刺人心 2021-01-07 16:19

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

相关标签:
4条回答
  • 2021-01-07 17:06

    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;
    
            // ...
        }
    
        // ...
    }
    
    0 讨论(0)
  • 2021-01-07 17:06

    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..

    0 讨论(0)
  • 2021-01-07 17:11

    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; }
    
        ...
    }
    
    0 讨论(0)
  • 2021-01-07 17:26

    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;"
      }
    }
    
    
    0 讨论(0)
提交回复
热议问题