Our code
Now that we have created our project, we need to talk about how we populate our program.cs
file. This is where our service will be spawned from, and where Topshelf will really show its power. Here's what our fully populated program.cs
file looks like. I have highlighted some areas that I want you to pay close attention to and understand:
static void Main(string[] args) { var builder = new ContainerBuilder();
Registering our service:
builder.RegisterType<MemoryMicroService>() .AsImplementedInterfaces() .AsSelf() ?.InstancePerLifetimeScope();
Registering our logger:
builder.RegisterType<Logger>().SingleInstance(); var container = builder.Build();
Watching for log4net
configuration changes:
XmlConfigurator.ConfigureAndWatch(new FileInfo(@".log4net.config")); HostFactory.Run(c => {
Using Autofac as our IoC:
c?.UseAutofacContainer(container); c?.UseLog4Net(); c?.ApplyCommandLineWithDebuggerSupport(); c?.EnablePauseAndContinue(); c?.EnableShutdown();
Trapping any general exceptions...