Home > Blockchain >  How to nicely load an object from the builder.configuration?
How to nicely load an object from the builder.configuration?

Time:08-29

I am working on a .NET Core Web API using Swagger with multiple Swagger endpoints inside. But my programs.cs becomes a bit crowded with the many options.SwaggerDoc("endpoint-name", more stuff... { ... even more stuff }); lines of code. But I need multiple endpoints as I have several services that all share the same data context, but I want to provide them as six different services. And this works fine! No problems here...
But I want the programs.cs to look cleaner by loading some information from the configuration file. Especially the 'License' and 'contact' with every endpoint as I don't want those hard-coded in my code. They need to be in the config.
So I need to have multiple OpenApiContact and OpenApiLicense records inside the appsettings.json and read them through the builder.Configuration to put them in the proper position. After all, this information needs to be configurable.
If the answer is to do something like:

var contact = new OpenApiContact
{
    Name = builder.Configuration["Service1:Name"],
    Email = builder.Configuration["Service1:Email"],
    Url = new Uri(builder.Configuration["Service1:Url"])
};

Then I'll be very unhappy... It pollutes...

CodePudding user response:

You can leverage build in configuration binding mechanisms (cleaned up json config):

{
  "Service1": {
    "Name": "qwewq",
    "Url": "https://stackoverflow.com/",
    "Email": "[email protected]"
  }
}
var contact = builder.Configuration.GetSection("Service1").Get<OpenApiContact>();

Or even binding to dictionary/array. For example with dictionary:

{
  "Services": {
    "Service1": {
      "Name": "qwewq",
      "Url": "https://stackoverflow.com/",
      "Email": "[email protected]"
    }
  }
}
var openApiContacts = builder.Configuration.GetSection("Services").Get<Dictionary<string, OpenApiContact>>();

CodePudding user response:

Well, it was simpler than expected. Just started trying and it worked! I now have this:

options.SwaggerDoc("Service1", builder.Configuration.GetSection("Swagger:Service1").Get<OpenApiInfo>());

And it loads the whole OpenApiInfo from the configuration. And inside the configuration I have this:

  "Swagger": {
    "Service1": {
      "Title": "Some title",
      "Description": "Some description.",
      "Contact": {
        "Name": "W.A. ten Brink",
        "Email": "[email protected]",
        "Url": "https://www.example.com"
      },
      "License": {
        "Name": "Example",
        "Url": "https://www.example.com/License/"
      },
      "Version": "1.0.0.1"
    },
...[more]...

And all the API information is now loaded from the configuration file. All this information is just informational so the administrators can change it if they like. If they misspell the service name or whatever then the endpoint is still there. It just has no information.

  • Related