-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServiceCollectionExtensions.cs
More file actions
79 lines (66 loc) · 2.99 KB
/
Copy pathServiceCollectionExtensions.cs
File metadata and controls
79 lines (66 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using GovUK.Dfe.CoreLibs.Caching.Interfaces;
using GovUK.Dfe.CoreLibs.Caching.Services;
using GovUK.Dfe.CoreLibs.Caching.Settings;
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
private static string GetRedisConnectionString(IConfiguration config)
{
// First, check ConnectionStrings:Redis
var connectionString = config.GetConnectionString("Redis");
if (!string.IsNullOrEmpty(connectionString))
{
return connectionString;
}
// Fall back to CacheSettings:Redis:ConnectionString
var cacheSettings = config.GetSection("CacheSettings:Redis").Get<RedisCacheSettings>();
if (!string.IsNullOrEmpty(cacheSettings?.ConnectionString))
{
return cacheSettings.ConnectionString;
}
throw new InvalidOperationException(
"Redis connection string is required but not configured. " +
"Please configure either 'ConnectionStrings:Redis' or 'CacheSettings:Redis:ConnectionString'");
}
public static IServiceCollection AddServiceCaching(
this IServiceCollection services, IConfiguration config)
{
services.Configure<CacheSettings>(config.GetSection("CacheSettings"));
services.AddMemoryCache();
services.AddSingleton<ICacheService<IMemoryCacheType>, MemoryCacheService>();
return services;
}
public static IServiceCollection AddRedisCaching(
this IServiceCollection services, IConfiguration config)
{
services.Configure<CacheSettings>(config.GetSection("CacheSettings"));
// Configure Redis connection
services.AddSingleton<IConnectionMultiplexer>(serviceProvider =>
{
var connectionString = GetRedisConnectionString(config);
return ConnectionMultiplexer.Connect(connectionString);
});
services.AddSingleton<ICacheService<IRedisCacheType>, RedisCacheService>();
return services;
}
public static IServiceCollection AddHybridCaching(
this IServiceCollection services, IConfiguration config)
{
services.Configure<CacheSettings>(config.GetSection("CacheSettings"));
// Add Memory Cache
services.AddMemoryCache();
services.AddSingleton<ICacheService<IMemoryCacheType>, MemoryCacheService>();
// Add Redis Cache
services.AddSingleton<IConnectionMultiplexer>(serviceProvider =>
{
var connectionString = GetRedisConnectionString(config);
return ConnectionMultiplexer.Connect(connectionString);
});
services.AddSingleton<ICacheService<IRedisCacheType>, RedisCacheService>();
return services;
}
}
}