Reputation: 1413
I am getting an error:
Error CS1503 Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<>
When I am using Configure with Bind(), it is working.
var bandConfig = new BandSettings();
Configuration.GetSection("BandSettings").Bind(bandConfig );
But with the below code, I am getting the above error.
I tried many solutions suggested in blogs and other forums, For example - Getting value from appsettings.json in .net core
but still the same error. Am I missing anything??
I have below things in place: appsettings.json
"BandSettings":{
"UserID": "aTestUserID",
"Password" : "aTestPassword"
}
BandSettings.cs
public class BandWidthSettings
{
public string UserID { get; set; }
public string ApiToken { get; set; }
}
TestHelper.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public static IConfiguration GetTestConfiguration()
=> new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
public IConfiguration Configuration { get; }
public TestHelper(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var config = new BandSettings();
var bandSettingsSection = Configuration.GetSection("BandSettings");
services.Configure<BandSettings>(bandSettingsSection); //Error is getting on this line - bandSettingsSection
}
Upvotes: 66
Views: 43647
Reputation: 31
I read people here suggesting add Microsoft.Extensions.Options.ConfigurationExtensions but sometimes packages are inside other packages like Serilog.AspNetCore Version=6.1.0.
Upvotes: 1
Reputation: 3330
Add NuGet package Microsoft.Extensions.Options.ConfigurationExtensions to get the extension method where
services.Configure<BandSettings>(Configuration.GetSection("BandSettings"));
will work.
Reference: https://github.com/dotnet/AspNetCore.Docs/issues/18833
Upvotes: 215
Reputation: 473
Create a POCO for the setting
public class MySetting
{
public string Setting{ get; set; }
}
On Startup it works perfectly as it should be:
services.Configure<MySetting>(Configuration.GetSection("MySetting"));
However on my the dependecy injection add the bind as mentioned in the question comments.
private static void ConfigureServices(IServiceCollection services)
{
var mySection = configuration.GetSection("MySetting");
services.Configure<MySetting>(c => mySection .Bind(c));
}
Upvotes: 6
Reputation: 1413
public IConfiguration Configuration { get; }
public TestHelper(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
//Configure section binding
services.Configure<BandSettings>(Configuration.GetSection(BandSettings.SECTION));
}
Upvotes: 2