How do I inject or pass IConfigurationRoot to service class in .netcore?

kikme
kikme
36 Points
13 Posts

How do I inject or pass IConfigurationRoot to service class in .netcore? I'm using  IConfigurationRoot  as a constructor parameter in the service class as:

public class SomeService : ISomeService {

     public SomeService(IConfigurationRoot configurationRoot){
        //do something
     }

}

And in startup.cs:

services.AddTransient<ISomeService, SomeService>();
Views: 53
Total Answered: 1
Total Marked As Answer: 0
Posted On: 07-Oct-2021 06:19

Share:   fb twitter linkedin
Answers
beginer
beginer
246 Points
73 Posts
         

Inject IConfigurationRoot object in startup:

services.AddSingleton<IConfigurationRoot>(Configuration);

See full startup.cs

public class Startup
{
    public Startup(IConfigurationRoot configuration)
    {
        Configuration = configuration;
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddSingleton<IConfigurationRoot>(Configuration);
        services.AddTransient<ISomeService, SomeService>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}
Posted On: 07-Oct-2021 23:32
 Log In to Chat