Last active
December 22, 2018 15:11
-
-
Save deepumi/ec52aa1e1fa760d4b48e477f9ce88318 to your computer and use it in GitHub Desktop.
Feature flag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
namespace FeatureFlagTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var home = new HomeController(FeatureFactory.Feature); | |
home.Index(); | |
var evnt = new EventSample(FeatureFactory.Feature); | |
evnt.Do(); | |
} | |
} | |
public interface IFeature | |
{ | |
bool IsOn(string feature); | |
} | |
public sealed class Feature : IFeature | |
{ | |
private readonly FeatureSettings _featureSettings; | |
public Feature(FeatureSettings featureSettings) => _featureSettings = featureSettings; | |
public bool IsOn(string feature) | |
{ | |
if (string.IsNullOrEmpty(feature) || !_featureSettings.ContainsKey(feature)) return false; | |
return _featureSettings[feature]; | |
} | |
} | |
public sealed class FeatureSettings : ConcurrentDictionary<string, bool> | |
{ | |
public FeatureSettings() : base(StringComparer.OrdinalIgnoreCase) { } | |
} | |
public sealed class FeatureFactory | |
{ | |
private static readonly Lazy<IFeature> _lazy = new Lazy<IFeature>(() => new Feature(GetFeatureSettings())); | |
private static FeatureSettings GetFeatureSettings() => new FeatureSettings | |
{ | |
["welcome"] = true, | |
["events"] = false | |
}; | |
public static IFeature Feature => _lazy.Value; | |
private FeatureFactory() { } | |
} | |
public sealed class HomeController | |
{ | |
private readonly IFeature _feature; | |
public HomeController(IFeature feature) => _feature = feature; | |
public void Index() | |
{ | |
if (_feature.IsOn("welcome")) | |
{ | |
//do something | |
} | |
} | |
} | |
public sealed class EventSample | |
{ | |
private readonly IFeature _feature; | |
public EventSample(IFeature feature) => _feature = feature; | |
public void Do() | |
{ | |
if (_feature.IsOn("ddd")) | |
{ | |
//do something | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment