15

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?

Blaise
  • 21,314
  • 28
  • 108
  • 169
  • [`UseStartup`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.webhostbuilderextensions.usestartup?view=aspnetcore-6.0) seems to still exist in ASP.NET Core 6, though I haven't yet updated to VS2022 so I can't test. – ProgrammingLlama Dec 21 '21 at 03:38
  • Does this answer your question? [How do I access Configuration in any class in ASP.NET Core?](https://stackoverflow.com/questions/39231951/how-do-i-access-configuration-in-any-class-in-asp-net-core) – JHBonarius Dec 21 '21 at 07:58
  • If you question is about accessing configuration during setup - see this [answer](https://stackoverflow.com/questions/69722872/asp-net-core-6-how-to-access-configuration-during-setup/69722959#69722959). Also you are not required to use the new minimal hosting model you can switch to the generic one if you want. – Guru Stron Dec 21 '21 at 10:13

3 Answers3

19

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);
Blaise
  • 21,314
  • 28
  • 108
  • 169
  • 3
    I have `'IServiceCollection' does not contain a definition for 'AddInfrastructureServices'`, and same for `AddPersistenceServices` (last two lines of your code) – Matthieu Charbonnier Jul 16 '22 at 11:11
  • I think the missing piece here is what you're doing with `config` inside your `AddInfrastructureServices` and `AddPersistenceServices` IServiceCollection extension methods. – Jerome Sep 23 '22 at 08:55
  • What can I do if I need to access IConfiguration in handler class? – Bronek Jan 16 '23 at 18:35
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...
    }
}
Marko
  • 12,543
  • 10
  • 48
  • 58
3

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
}
SH7
  • 732
  • 7
  • 20
  • 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?](https://softwareengineering.stackexchange.com/q/432807) – kkuilla Sep 26 '22 at 14:31