How do I access Configuration in any class in ASP.NET Core?

前端 未结 11 1684
梦如初夏
梦如初夏 2020-11-29 01:09

I have gone through configuration documentation on ASP.NET core. Documentation says you can access configuration from anywhere in the application.

Below is Startup.c

11条回答
  •  [愿得一人]
    2020-11-29 01:18

    I know this is old but given the IOptions patterns is relatively simple to implement:

    1. Class with public get/set properties that match the settings in the configuration

      public class ApplicationSettings
      {
          public string UrlBasePath { get; set; }
      }
      
    2. register your settings

      public void ConfigureServices(IServiceCollection services)
      {
       ...
       services.Configure(Configuration.GetSection("ApplicationSettings"));
      ...
      }
      
    3. inject via IOptions

      public class HomeController
      {
         public HomeController(IOptions appSettings)
         { ...
          appSettings.Value.UrlBasePath
          ...
          // or better practice create a readonly private reference
          }
       }
      

    I'm not sure why you wouldn't just do this.

提交回复
热议问题