Skip to content

Instantly share code, notes, and snippets.

@micdenny
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save micdenny/dc089ab6258a80a48435 to your computer and use it in GitHub Desktop.
Save micdenny/dc089ab6258a80a48435 to your computer and use it in GitHub Desktop.
Bootstrapper sample + Topshelf
using System;
using System.Timers;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Topshelf;
namespace TopshelfBootstrapper
{
internal class Program
{
private static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<Service>(s =>
{
s.ConstructUsing(name => new Service());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("Stuff");
x.SetServiceName("Stuff");
});
}
}
public class Service
{
private IWindsorContainer _container;
private IMyComponent _myComponent;
public Service()
{
_container = new WindsorContainer();
// registrations
_container.Register(
Component.For<IMyComponent>().ImplementedBy<MyComponent>()
);
}
public void Start()
{
// resolve entry resource
_myComponent = _container.Resolve<IMyComponent>();
// start
_myComponent.Start();
}
public void Stop()
{
if (_myComponent != null)
{
// stop
_myComponent.Stop();
}
if (_container != null)
{
// release entry resource (ALWAYS RELEASE WHAT YOU RESOLVE)
_container.Release(_myComponent);
// dipose the container!
_container.Dispose();
}
}
}
public interface IMyComponent
{
void Start();
void Stop();
}
public class MyComponent : IMyComponent
{
private readonly Timer _timer;
public MyComponent()
{
_timer = new Timer(1000) { AutoReset = true };
_timer.Elapsed += (sender, args) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
}
public void Start()
{
_timer.Start();
}
public void Stop()
{
_timer.Stop();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment