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.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.

About these ads

2 Comments »

  1. 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


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: