Skip to content

Instantly share code, notes, and snippets.

@phatboyg
Created November 5, 2014 23:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save phatboyg/dceaf56120f5382cdfa7 to your computer and use it in GitHub Desktop.
Save phatboyg/dceaf56120f5382cdfa7 to your computer and use it in GitHub Desktop.
Sample Topshelf service that demonstrates how features can be toggled using the Fooidity Switchyard
namespace ConsoleApplication2
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Fooidity;
using Topshelf;
class Program
{
static int Main(string[] args)
{
return (int)HostFactory.Run(x =>
{
x.Service(hostSettings => ServiceContainer.Container.Resolve<SampleService>(),
s => { s.AfterStoppingService(() => ServiceContainer.Container.Dispose()); });
});
}
}
class ServiceContainer
{
static readonly Lazy<IContainer> _container = new Lazy<IContainer>(CreateServiceContainer);
public static IContainer Container
{
get { return _container.Value; }
}
static IContainer CreateServiceContainer()
{
var builder = new ContainerBuilder();
builder.ConfigureFoodityClient(x =>
{
x.Host("http://api.fooidity.com/");
x.ApplicationKey("put your application key here from the web site");
});
builder.RegisterCodeSwitch<TestFeature>();
builder.RegisterType<SampleService>();
return builder.Build();
}
}
class SampleService :
ServiceControl
{
readonly CancellationTokenSource _cancel;
readonly ILifetimeScope _scope;
public SampleService(ILifetimeScope scope)
{
_scope = scope;
_cancel = new CancellationTokenSource();
Task.Run(() => Background(_cancel.Token));
}
public bool Start(HostControl hostControl)
{
Console.WriteLine("Started the service");
return true;
}
public bool Stop(HostControl hostControl)
{
Console.WriteLine("Stopped the service");
_cancel.Cancel();
return true;
}
async Task Background(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(1000, cancellationToken);
using (ILifetimeScope scope = _scope.BeginLifetimeScope())
{
Console.WriteLine("Switch: {0}", scope.Resolve<ICodeSwitch<TestFeature>>().Enabled);
}
}
}
}
public struct TestFeature :
ICodeFeature
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment