Home > Mobile >  Read appsetting.json content to "Data Layer" (Not To Controller) in dot net 5 application
Read appsetting.json content to "Data Layer" (Not To Controller) in dot net 5 application

Time:10-15

My appsettings.json looks something like following: { "Server": "ABC", "DefaultDatabase": "XYZ", "delayTimer" : 10,}

I have another class scheduler.cs(Data layer) in which I am reading "delayTimer" from Appsettings in the constructor as follows:

    public class Scheduler
    {    
       public Scheduler(IConfiguration configSrc)
       {           
          this.delayTime = configSrc.GetValue<int>("delayTimer");
          CallScheduler();
       }
    }

Now, I need to call this class from "Startup.cs" when the application is loading, but how do I create an instance of it? I am aware that as the Scheduler class is having constructor dependency then I may need to pass object of a class which implements "IConfiguration" interface. In Startup.cs, I am trying following:

    public void ConfigureServices(IServiceCollection services)
    {            
        services.AddControllers();

        services.AddSingleton(typeof(Config));
        services.AddSingleton(typeof(TokenHelper));
               
        // The next line gives an error: I need to pass a class object
        // implementing IConfiguration interface but when I try to
        // create a new class which implements IConfiguration it result
        // in errors.
        Scheduler obj = new Scheduler();
        services.AddSingleton<Scheduler>(obj);

        Thread t1 = new Thread(new ThreadStart(obj.CallScheduler));
        t1.Start();

My question: How do I read the appsettings.json value of "delayTimer" in data layer class??. I read lot of posts which speaks about reading the content from asppsetting to controller class. Example: Read asppsetting.json to controller but I am not looking for this requirement.

CodePudding user response:

You can read config in configureService and can provide config as below

.ConfigureServices((hostContext, services) =>
                        {
                            var config = hostContext.Configuration;
                            Scheduler obj = new Scheduler(config);
                        }

CodePudding user response:

I could fetch the value directly to my data layer class using this: new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("MyCustom")["delayTimer"]

Where MyCustom is the section of JSON file and delayTimer is the key I want to read.

  • Related