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.
This commit is contained in:
parent
c81ff2c628
commit
9d36ced82f
31
DigitalData.Core.Abstractions/ServiceProviderExtensions.cs
Normal file
31
DigitalData.Core.Abstractions/ServiceProviderExtensions.cs
Normal file
@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user