caloggins
2/25/2014 - 9:55 AM

FeatureToggles.cs


Component.
  For<IService>().
  ImplementedBy<Service>().
  FeatureToggle(Dependency.OnAppSettingsValue("FeatureToggle")),
  
Classes.
  FromAssemblyInDirectory(new AssemblyFilter(".")).
  BasedOn<ServiceBase>().
  If(FeatureToggles.IsEnabled(Dependency.OnAppSettingsValue("FeatureToggle"))).
  WithServiceBase(),
using System;
using System.Linq;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;

namespace Project.Installers {
  
  public static class FeatureToggles {
    
    static readonly string[] OnStates = { "on", "enabled" };
    static readonly IRegistration FeatureOff = new SkipRegistration();

    public static IRegistration FeatureToggle(this IRegistration feature, Parameter toggle) {
      if (IsEnabled(toggle.Value))
        return feature;
      return FeatureOff;
    }

    public static Predicate<Type> IsEnabled(Parameter toggle) {
      if (IsEnabled(toggle.Value))
        return _ => true;
      return _ => false;
    }

    static bool IsEnabled(string value) {
      return value == null || OnStates.Contains(value.Trim().ToLowerInvariant());
    }
  }

  class SkipRegistration : IRegistration {
    public void Register(IKernelInternal kernel) { }
  }
}