That seems to work for me:
Does it just default to Good
for you? Is your appsettings.json file being loaded correctly (+ set to 'Copy If Newer' for 'Copy to Output Directory')?
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
.Net 6 console app (generic host) using injected IOptions<MyServiceOptions> in service constructor.
The MyServiceOptions has a property which is an enum.
Setting the enums underlying integral value in appsettings.json works fine, but of course not intuitive to the user.
What can I do to have the enum string value in appsettings.json automatically converted to the correct enum integral value?
(Converter to be specified? attributes? etc?)
Configuration is read in IHostBuilder.ConfigureServices like this:
IHost host = Host.CreateDefaultBuilder(args)
.UseSerilog((ctx, config) =>
{
config.ReadFrom.Configuration(ctx.Configuration);
})
.ConfigureServices((hostContext, services) =>
{
services.Configure<MyServiceOptions>(hostContext.Configuration.GetSection("MyServiceOptions"));
services.AddSingleton<MyService>()
services.AddHostedService<MainService>();
})
.UseWindowsService()
.Build();
MyService thus depends on IOptions<MyServiceOptions>
MyServiceOptions:
public enum Quality
{
Good,
Bad,
Unknown
}
public class MyServiceOptions
{
public string Name { get; set; }
public Quality? Quality { get; set; }
}
My opinion on how appsettings.json could/should look like:
"MyServiceOptions": {
"Name": Item1,
"Quality": "Unknown"
}
That seems to work for me:
Does it just default to Good
for you? Is your appsettings.json file being loaded correctly (+ set to 'Copy If Newer' for 'Copy to Output Directory')?
Thanks
A bit embarrassing, but it works when I re-try, I think I must have had the enum misspelled when I tried first time and probably without the nullable, because what I saw was, as you cleverly ask, the default value of Good (if it was nullable it would be null instead).
So please forgive me asking stupid and wrong questions, but perhaps you know if it is possible to have an exception thrown if the enum (string) is none of the defined values?