Last active
August 29, 2015 14:13
-
-
Save micdenny/dc089ab6258a80a48435 to your computer and use it in GitHub Desktop.
Bootstrapper sample + Topshelf
This file contains 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.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