/
FeatureToggleFactory.cs
97 lines (81 loc) · 3.18 KB
/
FeatureToggleFactory.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
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
using System;
using System.Collections.Generic;
using System.Configuration;
using nToggle.Configuration;
namespace nToggle
{
public class FeatureToggleFactory : IFeatureToggleFactory
{
private readonly IFeatureToggleRepository _staticToggleRepository;
private readonly Dictionary<string, IFeatureToggleRepository> _toggleRepositoryDictionary;
private static FeatureToggleFactory _currentFactory;
public static FeatureToggleFactory CurrentFactory
{
get
{
if (_currentFactory == null)
{
_currentFactory = LoadFactory();
}
return _currentFactory;
}
set { _currentFactory = value; }
}
private static FeatureToggleFactory LoadFactory()
{
var config = (ToggleConfigurationSection) ConfigurationManager.GetSection(
"nToggle");
var toggleRepositoryDictionary = new Dictionary<String, IFeatureToggleRepository>();
var toggleValueDictionary = new Dictionary<String, bool>();
var staticToggleRepository = new StaticToggleRepository(toggleValueDictionary);
foreach (ToggleElement toggle in config.Toggles)
{
if (!toggle.Value || String.IsNullOrEmpty(toggle.Repository))
{
toggleRepositoryDictionary.Add(toggle.Name, staticToggleRepository);
toggleValueDictionary.Add(toggle.Name, toggle.Value);
}
else
{
var strings = toggle.Repository.Split(',');
var dynamicRepo =
(IFeatureToggleRepository) Activator.CreateInstance(strings[0], strings[1]).Unwrap();
toggleRepositoryDictionary.Add(toggle.Name,dynamicRepo);
}
}
return new FeatureToggleFactory(toggleRepositoryDictionary);
}
public FeatureToggleFactory(Dictionary<string, IFeatureToggleRepository> toggleRepositoryDictionary)
{
_toggleRepositoryDictionary = toggleRepositoryDictionary;
}
public IFeatureToggle GetFeatureToggle(string featureName, bool reversed)
{
bool statusFromRepository = false;
try
{
statusFromRepository = _toggleRepositoryDictionary[featureName].GetToggleStatus(featureName);
}
catch (KeyNotFoundException ex)
{
}
return new FeatureToggle(reversed ? !statusFromRepository : statusFromRepository);
}
public IFeatureToggle GetFeatureToggle(string featureName)
{
return GetFeatureToggle(featureName, false);
}
}
internal class StaticToggleRepository : IFeatureToggleRepository
{
private Dictionary<string, bool> _toggleValues;
public StaticToggleRepository(Dictionary<string, bool> values)
{
_toggleValues = values;
}
public bool GetToggleStatus(string toggleName)
{
return _toggleValues[toggleName];
}
}
}