Hinzufügen der ConfigureBySection-Methode zur Konfiguration von Diensten nach Abschnitt und Rückgabe des Builders.

This commit is contained in:
Developer 02 2024-06-11 18:57:44 +02:00
parent 63bcf8a9b9
commit cb28ce39a1

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Builder;
using System.Configuration;
namespace DigitalData.Core.API
{
@ -47,5 +48,22 @@ namespace DigitalData.Core.API
/// <param name="app">The WebApplication instance.</param>
/// <returns>True if the environment is Development or DiP mode is enabled; otherwise, false.</returns>
public static bool IsDevOrDiP(this WebApplication app) => app.Environment.IsDevelopment() || app.IsDiP();
}
/// <summary>
/// Configures the services with options from the specified section of the appsettings.json file.
/// </summary>
/// <typeparam name="T">The options class type. Must be a reference type.</typeparam>
/// <param name="builder">The WebApplicationBuilder instance.</param>
/// <returns>The WebApplicationBuilder instance for chaining.</returns>
/// <exception cref="InvalidOperationException">Thrown if the section is not found in the configuration.</exception>
public static WebApplicationBuilder ConfigureBySection<T>(this WebApplicationBuilder builder) where T : class
{
var section = builder.Configuration.GetSection(typeof(T).Name);
if (!section.Exists())
throw new InvalidOperationException($"Section '{typeof(T).Name}' not found in appsettings.");
builder.Services.Configure<T>(section);
return builder;
}
}
}