appsettings.json with enum

EuroEager2008 171 Reputation points
2021-11-28T11:04:02.783+00:00

.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"
      }
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
321 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,193 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. P a u l 10,406 Reputation points
    2021-11-28T11:22:02.32+00:00

    That seems to work for me:

    153131-image.png

    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')?

    0 comments No comments

  2. EuroEager2008 171 Reputation points
    2021-11-28T14:32:00.183+00:00

    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?


  3. Magne 126 Reputation points
    2021-11-30T14:18:14.367+00:00

    Thanks a lot @P a u l tested and working fine (of course)

    0 comments No comments