Tim Scott's Blog

March 30, 2012

Self-Hosting WebApi as a Windows Service with TopShelf

Filed under: C#, WebApi — Tim Scott @ 5:24 pm

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.Filters.Add(new ExceptionFilter());
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        server = new HttpSelfHostServer(config);

    public void Start()

    public void Stop()

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.SetDescription("Does really cool stuff.");
        x.SetDisplayName("My Web Api Service");

To create a Windows Service, run your console app with a switch.

MyWebApiService.SelfHost.exe install

That’s it! Enjoy.

Create a free website or blog at WordPress.com.