Search code examples
c#blazorblazor-server-sideappsettings

How to read appsetting.json from any class blazor serverside


i know how to acess to appsetting.json fron razor component but how from any class in a blazor serverside project?

from razor component i simply inject:

@inject IConfiguration _config

and access all that i need like : _config.GetConnectionString("default")

but how can do the same from any class? when i try to do

IConfiguration _config;

it says when i want to reach data that _config is null or is an unassigned local variable depands where i write the variable.


Solution

  • i understood how it work so i can answer my question myself

    in fact, you just have to add a constructor in your class with Iconfiguration as argumentand you can use it and call your data stored in your app setteing:

        public class MyClass 
    {
        public MyClass (IConfiguration config)
        {
            _config = config;
        }
    
    
        private readonly IConfiguration _config;
        
    
    
        void MyMethod(){
                .....
               }
    }
    

    You can use it after in your method:

    string myCon = _config.GetConnectionString("Default");