1

I have created a new Web API which contains a Program.cs (no startup.cs) and uses top level statements (i.e. does not have public class Program).

How do I add dependency injection to allow IOptions to be passed to any constructors I create? I have this working using the old Startup.cs, but I seem to be I'm missing something with the new format.

I have added

Program.cs:

var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();
builder.Services.Configure<IOptions<DbConfig>>(config.GetSection("ConnectionStrings"));

The class constructor looks like this:

public SqlClient(IOptions<DbConfig> Config)
        {
            _configuration = Config;
        }

Any calls to this function are showing an error "There is no argument given that corresponds to the parameter Config", i.e. it want's me to pass that parameter in from the calling code.

DbConfig has the 4 properties from the appsettings.json DatabaseConnection section. Appsettins.json:

"DatabaseConnection": {
    "DataSource": "xx.xx.xx.xx",
    "UserID": "ID",
    "Password": "PW",
    "InitialCatalog": "DB"
  }
  • 1
    use `builder.Services.Configure(config.GetSection("ConnectionStrings"));`. Remove the IOptions from the registration (keep using it when resolving). docs: [link](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0#combining-service-collection) (one of many examples) – lordvlad30 Mar 17 '23 at 09:35
  • Also, your config source should be `DatabaseConnection`, and not `ConnectionStrings` – DavidG Mar 17 '23 at 09:37

1 Answers1

0
  1. Configure already registers IOptions (and other related views like IOptionsSnapshot), so change Configure<IOptions<DbConfig>> to just Configure<DbConfig>
  2. Based on the sample json your section should be DatabaseConnection, not ConnectionStrings, so builder.Services.Configure<DbConfig>(config.GetSection("DatabaseConnection"));
  3. No need to manually build config, use builder.Configuration

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132