Are you using WebApi for your services. If not (and you’re a Microsoft shop), you should be.
I’m creating a REST service. I want to host it on a machine without IIS. No problem, WebApi supports self hosting. But in production, it really needs to run as a Windows Service, not a console app. How to do that? Enter TopShelf. TopShelf makes it easy to host a service either in a console or as a Windows Service.
My service class.
public class MyWebApiService { private readonly HttpSelfHostServer server; private readonly HttpSelfHostConfiguration config; public MyWebApiService(string baseAddress, IDependencyResolver resolver) { config = new HttpSelfHostConfiguration(baseAddress); config.ServiceResolver.SetResolver(resolver); config.Filters.Add(new ExceptionFilter()); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); server = new HttpSelfHostServer(config); } public void Start() { server.OpenAsync(); } public void Stop() { server.CloseAsync(); server.Dispose(); } }
And here’s how to make that service run under TopShelf.
static void Main(string[] args) { var container = Bootstrapper.RegisterDependencies(); var resolver = new StructureMapDependencyResolver(container); HostFactory.Run(x => { x.Service<MyWebApiService>(s => { s.SetServiceName("My Web Api Service"); s.ConstructUsing(name => new MyWebApiService(BASE_ADDRESS, resolver)); s.WhenStarted(svc => svc.Start()); s.WhenStopped(svc => svc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("Does really cool stuff."); x.SetDisplayName("My Web Api Service"); x.SetServiceName("MyWebApiService"); }); }
To create a Windows Service, run your console app with a switch.
MyWebApiService.SelfHost.exe install
That’s it! Enjoy.
Thanks for the post! I am trying to re-implement this, and I have a small snag. Is there something i need to reference for the StructureMapDependencyResolver? Also, the bootstrapper is requiring me to give it a type. Is this something you ran into as well? Sorry I’m pretty new to this stuff.
Comment by Chris — April 18, 2012 @ 5:17 pm
They are both my own classes. Actually StructureMapDependencyResolver I found somewhere on the interwebs. Maybe it was here: http://www.thecodinghumanist.com/blog/archives/2011/1/20/structuremap-and-asp-net-mvc-3-getting-started
Bootstrapper is simply a static where I initialize StructureMap.
Comment by Tim Scott — April 18, 2012 @ 6:31 pm