piotrwalat.net

Hosting Web API in Windows service

17 comments

Running your api as Windows services can have multiple advantages, especially when working on bigger projects. This allows for multiple (services to run in isolation and gives fine grained control over your system components.

ASP.NET Web API ships with self-hosting feature that allows to run HTTP service outside of IIS. This can be easily used in Windows services. In this blog post I am going to show how to host Web API service inside of Windows service, using both Windows Service Visual Studio project template and Topshelf library.

Please note that I am using Visual Studio 2012 RC and Web API nightly build NuGet packages in the following examples.

Project setup

Start off by creating a new Windows service project.

Now, add reference to ASP.NET Web API. I’m taking advantage of NuGet and nightly build packages, but Web API RC pieces should work as well. If you are looking for instructions, check this blog post by Henrik F Nielsen.

Implementation

The implementation is straightforward, we just need to create HttpSelfHostServer instance and call OpenAsync when the service starts.
For the sake of simplicity I’ve skipped logging and xml configuration (to configure service address).

Installation

The easiest way to install and test your service is using installutil.exe utility. Open your visual command prompt as administrator and go to bin\Debug folder of your service. To install it run:

To uninstall:

You may want to follow these instructions and add service installer along with a separate setup project to install your service. This would enable you to

Alternative approach – using Topshelf

Topshelf is a project aimed to simplify development and management of windows services. You can get it throught NuGet or download it on project’s website.

Let’s try to use it to host web api http server.

Create a new console applicaton and add a class library project to contain your service.

Please note that the service class is a plain object and does not extend any special classes. Topshelf uses logical services which makes them easily reusable outside of windows service context. I would say this is one of advantages over ‘classic’ approach presented earlier.

In your console app project you need to include hosting code. Topshelf gives you some flexibility on how you can actually host your service(s) (eg. shelving) , which is nicely decoupled from service implementation details.

This is basically all you need to do to implement a simple Web API service using Topshelf. To install it issue following command as administrator:

To uninstall:

Once you start your service,

you should be able to make HTTP requests to your self hosted Web API server.

That’s it! ASP.NET Web API self hosting features enabled us to use Windows service as a hosting process with minimal effort.

Written by Piotr Walat

June 10th, 2012 at 8:38 am

  • Andreas Gehrke

    Great article. I think you switched the code examples for the normal service implementation and the topshelf one.

    • Piotr Walat

      Thanks Andreas :) You are right – the implementations were switched, fixed it.

  • Pingback: Dew Drop – June 11, 2012 | Alvin Ashcraft's Morning Dew

  • http://codeslogs.blogspot.com Tun

    Really nice Article. It’s always good to learn something new like this.

    Thanks

  • Mike

    Wow, that’s pretty cool. But how do you choose the port, and how do you know if it’s free? That would probably be a config setting in real life right?

    • Piotr Walat

      Yeah, Mike you would probably want to use app.config and for example ApplicationSettings entry to configure the port as well as other stuff (routing path maybe?)

  • http://www.home-server-addins.com Andreas M.

    Nice article. Thanks a lot for going into the details. ATM, I’m trying to deploy a MVC 4 Web-Api project that’s targeted against .NET 4.0 to IIS 7.5 but can’t get it to run (always spits out error 500 with no useful log information). Do you know where I could find information on how to do this or even do a blog post yourself and show us how it’s done? Thanks a lot!

    • Piotr Walat

      Feel free to drop me an email with the project if you want. These are pretty random guesses but make sure that ASP.NET is registered in IIS (aspnet_regiis.exe -i) and that the app pool for your project runs on .NET 4.0 and not 2.0.

  • nap

    Thanks so much, this is working great and also for pointing to TopShelf, which is a great project and made service deployment and updating very easy.

  • http://www.syneity.com Pramod

    Nice one!! Thanks for introducing topshelf, with this combination of the hosting web api & the windows service, it is a killer. This info will surely help me in building something…

  • Pingback: Interesting .NET Links – June 20, 2012 | TechBlog

  • Stig

    This is great. Did not know about topshelf. Thanks for sharing!

  • Pingback: Remote printing with ASP.NET Web API in Windows Service | StrathWeb

  • Bossini Gianni

    Great, but please comment SetServiceName method as shown later

    x.Service(s =>
                            {
                                //s.SetServiceName(“Piotr.WebApiTopShelfService”);
                                s.ConstructUsing(name => new HttpApiService(new Uri(“http://localhost:1234″)));
                                s.WhenStarted(tc => tc.Start());
                                s.WhenStopped(tc => tc.Stop());
                            });

  • Peter Wijnhorst

    The TopShelf example seems to be incorrect, The SetServiceName is called on the service instead of the configuration (tried it with TopShelf version 3.1.106.0).
    Thanks for the great example

  • http://twitter.com/aheil Andreas Heil

    Thanks for sharing this ! I was looking exactly for this type of self hosting.

  • Pingback: Microsoft exam 70-487 study guide | alertcoding