Files
git.stella-ops.org/src/__Libraries/StellaOps.Provcache/ProvcacheServiceCollectionExtensions.cs

86 lines
3.0 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace StellaOps.Provcache;
/// <summary>
/// Extension methods for registering Provcache services.
/// </summary>
public static partial class ProvcacheServiceCollectionExtensions
{
/// <summary>
/// Adds Provcache services to the service collection.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="configuration">The configuration section.</param>
/// <returns>The service collection for chaining.</returns>
public static IServiceCollection AddProvcache(
this IServiceCollection services,
IConfiguration configuration)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configuration);
var section = configuration.GetSection(ProvcacheOptions.SectionName);
// Register options
services.AddOptions<ProvcacheOptions>()
.Bind(section)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions<LazyFetchHttpOptions>()
.Bind(section.GetSection(LazyFetchHttpOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
// Register core services
services.AddSingleton<IProvcacheService, ProvcacheService>();
// Register write-behind queue as hosted service
services.AddSingleton<IWriteBehindQueue, WriteBehindQueue>();
services.AddHostedService<WriteBehindQueueHostedService>();
services.AddHttpClient(HttpChunkFetcher.HttpClientName);
services.AddProvcacheInvalidators();
return services;
}
/// <summary>
/// Adds Provcache services with custom options.
/// </summary>
/// <param name="services">The service collection.</param>
/// <param name="configure">Action to configure options.</param>
/// <returns>The service collection for chaining.</returns>
public static IServiceCollection AddProvcache(
this IServiceCollection services,
Action<ProvcacheOptions> configure)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configure);
// Register options
services.AddOptions<ProvcacheOptions>()
.Configure(configure)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions<LazyFetchHttpOptions>()
.ValidateDataAnnotations()
.ValidateOnStart();
// Register core services
services.AddSingleton<IProvcacheService, ProvcacheService>();
// Register write-behind queue as hosted service
services.AddSingleton<IWriteBehindQueue, WriteBehindQueue>();
services.AddHostedService<WriteBehindQueueHostedService>();
services.AddHttpClient(HttpChunkFetcher.HttpClientName);
services.AddProvcacheInvalidators();
return services;
}
}