Running your API as Windows services can has 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 This allows to run HTTP service outside of IIS. This can is 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 Vis UAL Studio project Template Andtopshelf Library.
Please note that I am using Visual Studio + RC and Web API nightly build NuGet packages in the following examples.
Project Setup
Start off by creating a new Windows service project.
Now, the 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 is looking for instructions, check the This blog post by Henrik F Nielsen.
Implementation
The implementation is straightforward, we just need to create httpselfhostserver instance and call OpenAsync when the Serv Ice starts.
For the sake of simplicity I ' ve skipped logging and XML configuration (to configure service address).
public partial class Httpapiservice:servicebase { private httpselfhostserver _server; Private ReadOnly httpselfhostconfiguration _config; Public Const string serviceaddress = "http://localhost:2345"; Public Httpapiservice () { InitializeComponent (); _config = new Httpselfhostconfiguration (serviceaddress); _config. Routes.maphttproute ("Defaultapi", "Api/{controller}/{id}", new {id = routeparameter.optional}); } protected override void OnStart (string[] args) { _server = new Httpselfhostserver (_config); _server. OpenAsync (); } protected override void OnStop () { _server. Closeasync (). Wait (); _server. Dispose (); }}
public class Apiservicecontroller:apicontroller {public string Get () { return ' Hello from Windows service! "; }}
Installation
The easiest-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:
InstallUtil Piotr.ApiWindowsService.Service.exe
To uninstall:
Installutil/u Piotr.ApiWindowsService.Service.exe
Want to follow these instructions and add service installer along with a separate setup project to install your SE Rvice. This would enable
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 the IT to host Web API HTTP server.
Create A new console Applicaton and add a class library project to contain your service.
public class Httpapiservice {private readonly httpselfhostserver _server; Private ReadOnly httpselfhostconfiguration _config; Private Const string EventSource = "Httpapiservice"; Public Httpapiservice (Uri address) {if (! EventLog.SourceExists (EventSource)) {EventLog.CreateEventSource (EventSource, "Application"); } eventlog.writeentry (EventSource, String.Format ("Creating server at {0}", address. ToString ())); _config = new Httpselfhostconfiguration (address); _config. Routes.maphttproute ("Defaultapi", "Api/{controller}/{id}", new {id = routeparameter.optional} ); _server = new Httpselfhostserver (_config); } public void Start () {EventLog.WriteEntry (EventSource, "Opening httpapiservice server."); _server. OpenAsync (); } public void Stop () {_server. Closeasync (). Wait (); _server. Dispose (); }}
Please note that the service class was 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 the advantages over ' classic ' approach presented earlier.
In your console app for project need to include hosting code. Topshelf gives you some flexibility on how can actually host your service (s) (eg.shelving), which is nicely decoupled From service implementation details.
static void Main (string[] args) { hostfactory.run (x = { x.service
This is basically any need to does to implement a simple Web API service using Topshelf. To install it issue following command as administrator:
Piotr.WebApiTopShelfService.exe Install
To uninstall:
Piotr.WebApiTopShelfService.exe Uninstall
Once You start your service,
You should is able to make HTTP requests to your self hosted Web API server.
That ' s it! The ASP. NET Web API self hosting features enabled us to use Windows service as a hosting process with minimal effort.
Hosting Web API in Windows service