PortBlog.API/Shared/KBR.Cache/Extensions/ServiceCollectionExtensions.cs
Bangara Raju Kottedi 2533b5298f Support encrypted cache conn strings & update dependencies
Moved DecryptConnectionString to KBR.Shared.Extensions for reuse and improved configuration access. Added Encryption property to CacheOptions and appsettings for conditional decryption of cache connection strings. Updated ServiceCollectionExtensions to decrypt SQL Server cache connection strings when needed. Upgraded NuGet packages across projects to latest .NET 8/10.0.x versions. Included minor code cleanups and OpenApiSecurityScheme improvements.
2026-02-15 14:22:22 +05:30

54 lines
2.0 KiB
C#

using KBR.Cache.Constants;
using KBR.Cache.Options;
using KBR.Shared.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Diagnostics.CodeAnalysis;
namespace KBR.Cache.Extensions
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCache([NotNull] this IServiceCollection services, IConfiguration configuration)
{
// Ensure the 'Microsoft.Extensions.Options.ConfigurationExtensions' package is referenced in your project
var cacheOptions = configuration.GetSection("Cache").Get<CacheOptions>();
if (cacheOptions == null || cacheOptions.Provider == CacheProviders.InMemory)
{
services.AddDistributedMemoryCache();
}
else if (cacheOptions.Provider == CacheProviders.SqlServer)
{
var connectionString = cacheOptions.ConnectionString;
if ((bool)cacheOptions.Encryption)
{
connectionString = configuration.DecryptConnectionString(connectionString);
}
services.AddDistributedMySqlCache(options =>
{
options.ConnectionString = connectionString;
options.TableName = "Cache";
});
}
else if (cacheOptions.Provider == CacheProviders.Redis)
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = cacheOptions.ConnectionString;
options.InstanceName = "SampleInstance";
});
}
else
{
throw new Exception("Cache options are not valid");
}
services.TryAddSingleton<IAppDistributedCache, AppDistributedCache>();
return services;
}
}
}