43 lines
1.7 KiB
C#
43 lines
1.7 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace WebAccess.MCP.WebCache;
|
|
|
|
internal static class WebCacheServiceCollectionExtensions
|
|
{
|
|
internal const string ConnectionStringName = "WebCache";
|
|
|
|
public static IServiceCollection AddWebCachePersistence(
|
|
this IServiceCollection services,
|
|
IConfiguration configuration)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(services);
|
|
ArgumentNullException.ThrowIfNull(configuration);
|
|
|
|
services
|
|
.AddOptions<WebCacheOptions>()
|
|
.Bind(configuration.GetSection(WebCacheOptions.SectionName));
|
|
services.AddSingleton<IValidateOptions<WebCacheOptions>, WebCacheOptionsValidator>();
|
|
services.AddDbContextFactory<WebCacheDbContext>(options =>
|
|
{
|
|
var connectionString = configuration.GetConnectionString(ConnectionStringName);
|
|
if (string.IsNullOrWhiteSpace(connectionString))
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"ConnectionStrings:{ConnectionStringName} is required when cache persistence is used.");
|
|
}
|
|
|
|
options.UseNpgsql(connectionString);
|
|
});
|
|
services.TryAddSingleton(
|
|
serviceProvider => new Lazy<IDbContextFactory<WebCacheDbContext>>(
|
|
serviceProvider.GetRequiredService<IDbContextFactory<WebCacheDbContext>>));
|
|
services.TryAddSingleton(TimeProvider.System);
|
|
services.TryAddSingleton<IWebCacheRepository, PostgresWebCacheRepository>();
|
|
services.TryAddSingleton<IWebCacheService, WebCacheService>();
|
|
|
|
return services;
|
|
}
|
|
}
|