How to get appsettings config data in program ?

Hi i need to register an object in ServiceCollection that require information from the AzureStorageConfig
8 Replies
Yawnder
Yawnder3y ago
Then bind the configuration to your class. You need another nuget for that iirc, Microsoft.Extensions.Configuration.Binder. You would do something like var myConfiguration = configuration.Get<MyClass>("MySection")
TotechsStrypper
TotechsStrypperOP3y ago
I tried it but when request the BlobContainer these 2 null
TotechsStrypper
TotechsStrypperOP3y ago
I dont know how to use the binding
Yawnder
Yawnder3y ago
@TotechsStrypper var settings = configuration.GetSection("MyConfigurationNode").Get<MySettingsClass>(); So in your case, just builder.Configuration rather than configuration.
Mayor McCheese
services.AddSingleton(provider => { var options = provider.GetRequiredService<IOptions<MyClass>>(); return new BlobContainerClient(blahblahblah); }); I personally wouldn't read directly from configuration in a non configuration map class unless there was no other option.
jcotton42
jcotton423y ago
@TotechsStrypper $options
MODiX
MODiX3y ago
{
"My": {
"Foo": {
"Kix": 5
}
}
}
{
"My": {
"Foo": {
"Kix": 5
}
}
}
public class FooOptions
{
public const string SectionName = "My:Foo";

public string Bar {get;set;} = "default value for bar";
public int Kix {get;set;} = -1;
public DateTime? Pouet {get;set;} = default;
}

public static IServiceCollection AddFoo(this IServiceCollection services) =>
services
.AddOptions<FooOptions>()
.Configure<IConfiguration>((options, configuration) => configuration.Bind(FooOptions.SectionName, options))
.Validate(options => options.Kix >= 0, $"The configuration key '{FooOptions.SectionName}:{nameof(Kix)}' cannot be negative")
;

public static IServiceCollection AddFoo(this IServiceCollection services, Action<FooOptions> configure) =>
services
.AddFoo()
.Configure(configure);

//Startup:
services.AddFoo();
// or
services.AddFoo(fooOptions => fooOptions.Kix = 12);
public class FooOptions
{
public const string SectionName = "My:Foo";

public string Bar {get;set;} = "default value for bar";
public int Kix {get;set;} = -1;
public DateTime? Pouet {get;set;} = default;
}

public static IServiceCollection AddFoo(this IServiceCollection services) =>
services
.AddOptions<FooOptions>()
.Configure<IConfiguration>((options, configuration) => configuration.Bind(FooOptions.SectionName, options))
.Validate(options => options.Kix >= 0, $"The configuration key '{FooOptions.SectionName}:{nameof(Kix)}' cannot be negative")
;

public static IServiceCollection AddFoo(this IServiceCollection services, Action<FooOptions> configure) =>
services
.AddFoo()
.Configure(configure);

//Startup:
services.AddFoo();
// or
services.AddFoo(fooOptions => fooOptions.Kix = 12);
TotechsStrypper
TotechsStrypperOP3y ago
I use the service provider to get the job done

Did you find this page helpful?