33 lines
1.6 KiB
C#
33 lines
1.6 KiB
C#
#if NET
|
|
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;
|
|
}
|
|
#endif |