Proper way to inject custom configuration

The problem to solve: There is a list of settings lets say:

{
   "Kind1":
     {"attr1":"val11"},
     {"attr2":"val12"},
   "Kind2":
     {"attr1":"val21"},
     {"attr2":"val22"},       
}

and a consumer class (controller) in .NET Core 2.1, needs to access the above configuration to use Kind1 or Kind2.

Supposing corresponding class is already defined in C#:

 public class KindSetting
 {
    public string attr1{get;set;}
    public string attr2{get;set;}
 }

Now what is the best way of inject the configuration into the consumer object.

Is there a way to inject an IConfiguration instance into the consumer object and use it like this?:

KindSetting kindSetting =_configuration.GetValue<KindSetting>(kindSettingKey);

Is there any better approach to fulfill the above requirement?

2 answers

  • answered 2018-06-25 07:17 Diptee Hamdapurkar

    In the startup.com file, in the configureservices method you can do a configuration. sample code below:

       // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Need to add following linse
            services.Configure<KindSetting>(Configuration.GetSection("Kind1"));
         }
    

  • answered 2018-06-25 08:36 Milan Vidakovic

    After adding services.Configure<KindSettings>, you can inject configuration via DI by adding to your constructor.

    IOptionsSnapshot<KindSettings> kindSettingsConfiguration
    

    or

    IOptions<KindSettings> kindSettingsConfiguration
    

    The difference is, IOptionsSnapshot will reflect live changes in your config file, while IOptions is for singleton use.

    Hope it helps.