DigitalData.Core/DigitalData.Core.Abstractions/ServiceProviderExtensions.cs
Developer 02 9d36ced82f feat: Hinzufügen von Erweiterungsmethoden zum Abrufen von Konfigurationsoptionen von IServiceProvider
- Implementiert GetOptions<TOptions> zum Abrufen von Optionen oder null.
- Implementiert GetRequiredOptions<TOptions> für den Abruf von Optionen oder das Auslösen einer Ausnahme.
2025-04-28 16:10:31 +02:00

32 lines
1.6 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace DigitalData.Core.Abstractions;
/// <summary>
/// Extension methods for <see cref="IServiceProvider"/> to retrieve configuration options.
/// </summary>
public static class ServiceProviderExtensions
{
/// <summary>
/// Retrieves an instance of <typeparamref name="TOptions"/> from the <see cref="IServiceProvider"/>.
/// If the options are not registered, returns null.
/// </summary>
/// <typeparam name="TOptions">The type of the options to retrieve.</typeparam>
/// <param name="service">The service provider instance.</param>
/// <returns>An instance of <typeparamref name="TOptions"/> or null if not found.</returns>
public static TOptions? GetOptions<TOptions>(this IServiceProvider service) where TOptions : class
=> service.GetService<IOptions<TOptions>>()?.Value;
/// <summary>
/// Retrieves an instance of <typeparamref name="TOptions"/> from the <see cref="IServiceProvider"/>.
/// Throws an exception if the options are not registered.
/// </summary>
/// <typeparam name="TOptions">The type of the options to retrieve.</typeparam>
/// <param name="service">The service provider instance.</param>
/// <returns>An instance of <typeparamref name="TOptions"/>.</returns>
/// <exception cref="InvalidOperationException">Thrown when the options are not registered.</exception>
public static TOptions GetRequiredOptions<TOptions>(this IServiceProvider service) where TOptions : class
=> service.GetRequiredService<IOptions<TOptions>>().Value;
}