-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
PolicyLoader.cs
63 lines (52 loc) · 2.19 KB
/
PolicyLoader.cs
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
using Bet.Extensions.Resilience.Abstractions.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Polly;
using Polly.Registry;
namespace Bet.Extensions.Resilience.Abstractions;
public class PolicyLoader<TPolicy, TOptions> where TPolicy : IsPolicy where TOptions : PolicyOptions
{
private readonly ILogger<PolicyLoader<TPolicy, TOptions>> _logger;
private readonly IPolicyRegistry<string> _policyRegistry;
private readonly PolicyBucketOptions<TOptions> _policyProfileOptions;
private TOptions _options;
public PolicyLoader(
PolicyBucketOptions<TOptions> policyProfileOptions,
IOptionsMonitor<TOptions> optionsMonitor,
IPolicyRegistry<string> policyRegistry,
ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<PolicyLoader<TPolicy, TOptions>>();
_policyRegistry = policyRegistry ?? throw new ArgumentNullException(nameof(policyRegistry));
_options = optionsMonitor.Get(policyProfileOptions.Name);
optionsMonitor.OnChange((options, name) =>
{
if (name == policyProfileOptions.Name)
{
_options = options;
GetPolicy();
}
});
_policyProfileOptions = policyProfileOptions ?? throw new ArgumentNullException(nameof(policyProfileOptions));
}
public IsPolicy GetPolicy()
{
var policy = _policyProfileOptions.ConfigurePolicy(_options, _logger);
AddPolicy(_options.Name, () => policy, true);
return _policyProfileOptions.ConfigurePolicy(_options, _logger);
}
public PolicyLoader<TPolicy, TOptions> AddPolicy(string policyName, Func<IsPolicy> policyFunc, bool replaceIfExists = false)
{
if (!_policyRegistry.ContainsKey(policyName))
{
_policyRegistry.Add(policyName, policyFunc());
_logger.LogDebug("{policyName} was successfully added to Polly registry", policyName);
}
else if (replaceIfExists)
{
_policyRegistry[policyName] = policyFunc();
_logger.LogDebug("{policyName} was successfully updated with Polly registry", policyName);
}
return this;
}
}