-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandler.cs
More file actions
177 lines (148 loc) · 6.58 KB
/
Handler.cs
File metadata and controls
177 lines (148 loc) · 6.58 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
using CacheIt.Options;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CacheIt.Hosting
{
internal class Handler : IHostedService
{
#region .: Properties :.
private readonly TimeSpan _refreshInterval;
private readonly ILogger<Handler> _logger;
private readonly IServiceProvider _provider;
private CancellationToken _cancellationToken;
private HashSet<Type> _cacheableComponents;
private HashSet<Type> _cacheableTypes;
private HashSet<Type> _cacheableTypesInterfaces;
private readonly IOptionsMonitor<CustomRefreshOptions> _customRefreshOptions;
#endregion
#region .: Constructor :.
public Handler(
IConfiguration configuration,
ILogger<Handler> logger,
IServiceProvider provider,
IOptionsMonitor<CustomRefreshOptions> customRefreshOptions)
{
_logger = logger;
_provider = provider;
_customRefreshOptions = customRefreshOptions;
var refreshIntervalSection = configuration.GetSection("CacheIt:RefreshInterval");
if(refreshIntervalSection.Value is not null)
{
TimeSpan defaultRefreshInterval = TimeSpan.FromMinutes(1);
TimeSpan refreshInterval;
var parseSuccess = TimeSpan.TryParse(refreshIntervalSection.Value, out refreshInterval);
_refreshInterval = parseSuccess ? refreshInterval : defaultRefreshInterval;
}
else
{
_refreshInterval = TimeSpan.FromMinutes(configuration.GetValue<double>("CacheIt:RefreshIntervalMinutes", 1));
}
_cacheableTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(t => t.GetInterfaces().Contains(typeof(ICacheable)))
.ToHashSet();
_cacheableTypesInterfaces = _cacheableTypes
.SelectMany(type => type.GetInterfaces().Where(type => type != typeof(ICacheable)))
.ToHashSet();
_cacheableComponents = _cacheableTypes
.Concat(_cacheableTypesInterfaces)
.ToHashSet();
}
#endregion
#region .: Methods :.
private async Task LoadAll()
{
foreach (Type cacheableComponent in _cacheableComponents)
{
var component = (ICacheable)_provider.GetService(cacheableComponent);
if (component != null)
await component.Load();
}
}
private async Task ExecuteDefaultRefreshAsync()
{
while (!_cancellationToken.IsCancellationRequested)
{
await Task.Delay(_refreshInterval);
_logger.LogDebug("Starting to refresh Cacheables..");
try
{
foreach (Type cacheableComponent in _cacheableComponents)
{
var component = (ICacheable)_provider.GetService(cacheableComponent);
if (component != null && !_customRefreshOptions.CurrentValue.RefreshTimesByCacheableName.ContainsKey(cacheableComponent.Name))
_ = component.Refresh().ConfigureAwait(false);
}
}
catch (Exception err)
{
_logger.LogError(err, "Error when refreshing Cacheables");
}
}
}
private Task ExecuteCustomRefreshAsync()
{
foreach(var configuration in _customRefreshOptions.CurrentValue.RefreshTimesByCacheableName)
{
var componentType = _cacheableComponents.FirstOrDefault(component => component.Name == configuration.Key);
if(componentType == default)
continue;
var component = (ICacheable)_provider.GetService(componentType);
if (component != null)
_ = Task.Run(async () => {
_logger.LogDebug("Found custom refresh for a Cacheable! Cacheable= {Cacheable} Interval= {Interval}", configuration.Key, configuration.Value);
var configurationKey = configuration.Key;
while (!_cancellationToken.IsCancellationRequested)
{
if(_customRefreshOptions.CurrentValue.RefreshTimesByCacheableName.TryGetValue(configurationKey, out TimeSpan currentRefreshInterval))
{
await Task.Delay(currentRefreshInterval);
_logger.LogDebug("Starting to refresh Cacheable! Cacheable= {Cacheable} Interval= {Interval}", configuration.Key, currentRefreshInterval);
try
{
_ = component.Refresh().ConfigureAwait(false);
}
catch (Exception err)
{
_logger.LogError(err, "Error when refreshing Cacheable. Cacheable= {Cacheable} Interval= {Interval}", configuration.Key, currentRefreshInterval);
}
}
}
}, cancellationToken: _cancellationToken);
}
return Task.CompletedTask;
}
#endregion
#region .: IHostedService Methods Implementation :.
public async Task StartAsync(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
try
{
await LoadAll();
_ = ExecuteDefaultRefreshAsync();
_ = ExecuteCustomRefreshAsync();
_logger.LogDebug("Successfully Started Cacheable Hosted Refresh!");
}
catch (Exception err)
{
_logger.LogError(err, "Error when Starting Hosted Cacheables Refresh");
throw;
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
return Task.CompletedTask;
}
#endregion
}
}