How to inject IConfiguration in asp.net core 6
Asked Answered
G

3

20

There is no Startup.cs in the web/api application any more.

We used to be able to inject IConfiguration into that Startup class.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration
    }
    ...
}

Now that those add service and configuration code is moved into Program.cs, what is the correct way to access configuration from there?

Graiggrail answered 21/12, 2021 at 3:36 Comment(3)
UseStartup seems to still exist in ASP.NET Core 6, though I haven't yet updated to VS2022 so I can't test.Hypersensitive
Does this answer your question? How do I access Configuration in any class in ASP.NET Core?Storied
If you question is about accessing configuration during setup - see this answer. Also you are not required to use the new minimal hosting model you can switch to the generic one if you want.Residential
G
20

The IConfiguration can be accessed in the WebApplicationBuilder.

enter image description here

So no need to inject IConfiguration any more, it is now a property in the builder in Program.cs. enter image description here

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;

builder.Services.AddInfrastructureServices(config);
builder.Services.AddPersistenceServices(config);
Graiggrail answered 21/12, 2021 at 15:21 Comment(3)
I have 'IServiceCollection' does not contain a definition for 'AddInfrastructureServices', and same for AddPersistenceServices (last two lines of your code)President
I think the missing piece here is what you're doing with config inside your AddInfrastructureServices and AddPersistenceServices IServiceCollection extension methods.Deduce
What can I do if I need to access IConfiguration in handler class?Discernment
D
6

As far as I can tell, they replaced it with a concrete instance of ConfigurationManager class which is a property of the WebApplicationBuilder.

In your Program.cs class there is a line of code:

 var builder = WebApplication.CreateBuilder(args);

You can then access the configuration from this builder instance:

 builder.Configuration.GetConnectionString("DefaultConnection");

I know this does not answer your "how to inject IConfiguration" question but I'm guessing you just want to be able to access your configuration settings. There is nothing stopping you from setting up the project as it used to be in the old .net 5 code. All you need is Program.cs to be:

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        await host.RunAsync();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                webBuilder.ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Trace);
                });
            });
}

And then just create a class called Startup.cs with the following code:

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

    private IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // TODO: Service configuration code here...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // TODO: App configuration code here...
    }
}
Dianthe answered 21/12, 2021 at 4:37 Comment(0)
M
5

You could add the IConfiguration instance to the service collection as a singleton object in ConfigureServices:

public void ConfigureServices(IServiceCollection service)
{ 
    services.AddSingleton<IConfiguration>(Configuration);  
    //...
}

This allows you to inject IConfiguration in any controllers or classes:

public class UserController
{
  public UserController(IConfiguration configuration)   
  //Use IConfiguration instance here
}
Mesa answered 21/12, 2021 at 4:23 Comment(1)
Don't do this. A singleton will last for the lifetime of the application. In case of a web application, the lifetime of the web server. You would have to restart the web server to get the new instance. Other reasons: Is it a bad practice to use Singleton for DI in Asp.net rather than Scoped, Transient whenever possible?Dirigible

© 2022 - 2024 — McMap. All rights reserved.