Skip to content

Instantly share code, notes, and snippets.

@deepumi
Last active December 22, 2018 15:11
Show Gist options
  • Save deepumi/ec52aa1e1fa760d4b48e477f9ce88318 to your computer and use it in GitHub Desktop.
Save deepumi/ec52aa1e1fa760d4b48e477f9ce88318 to your computer and use it in GitHub Desktop.
Feature flag
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