-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoadBalancer.cs
54 lines (44 loc) · 1.72 KB
/
LoadBalancer.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
namespace LB.Core
{
public interface IProviderRegistration
{
}
public class LoadBalancer : IProvider
{
private readonly List<IProvider> providers = new();
private readonly Func<IReadOnlyCollection<IProvider>, IProvider> providerPickFunc;
public uint MaxProvidersCount { get; }
public IReadOnlyCollection<IProvider> Providers => this.providers;
public LoadBalancer(
uint maxProvidersCount,
Func<IReadOnlyCollection<IProvider>, IProvider> providerPickFunc,
params IProvider[] providers)
{
this.MaxProvidersCount = maxProvidersCount;
this.providerPickFunc = providerPickFunc;
this.RegisterProviders(providers);
}
public string Get()
{
if (this.Providers.Count == 0)
{
throw new LoadBalancerException($"There are no {nameof(IProvider)}s registered in the {nameof(LoadBalancer)}!");
}
return this.providerPickFunc(this.Providers).Get();
}
private void RegisterProviders(params IProvider[] providers)
{
if (!this.CanAddProviders(providers.Length))
{
var errorMessage = $"{nameof(LoadBalancer)} accepts up to {this.MaxProvidersCount} providers but" +
$" {providers.Length} more providers were passed and {this.Providers.Count} were already registered.";
throw new LoadBalancerException(errorMessage);
}
this.providers.AddRange(providers);
}
private bool CanAddProviders(int count)
{
return this.Providers.Count + count <= this.MaxProvidersCount;
}
}
}