Search code examples
c#asp.net-web-apiconsole-applicationtopshelf

Hosting a real WEB API project instead of a simple class


I have read several articles about how does TopShelf works. All of them are saying:

  • Create a Console application

  • Add the Topshelf NuGet package

  • Create a simple testController : ApiController to represent the service logic (I want to have my existing WEB API project to be hosting instead of this testController)

  • ...

But now I want to have my existing WEB API project to be hosting instead of this testController. How should I replace my project with this testController in this TopShelf console application?

Obviously I can't configure my WEB API project itself with TopShelf instead of using a Console Application because the WEB API has not an exe file like console app.

I just want to know how should I replace this test controller inside console app with my real API project?


Solution

    1. Add a new console application to your solution

    2. Install NuGet Package Microsoft.Owin.SelfHost, Microsoft.AspNet.WebApi.OwinSelfHost and Topshelf to the your new project

    3. Add a Startup.cs (see here)

    4. Add TopshelfService.cs

      public class TopshelfService
      {
          private IDisposable moDisposable = null;
      
          public void Start()
          {
              this.moDisposable = WebApp.Start<Startup>("http://localhost:9989");
          }
      
          public void Stop()
          {
              this.moDisposable?.Dispose();
          }
      }
      
    5. Add code from Topshelf Section to your Main methode

    6. Add a reference to your existing WebApi Project

    7. Create a dummy instance from you controller in your Startup class. (This is necessary to load you WebApi Project before start Owin)

      public void Configuration(IAppBuilder app)
      {
          DemoController dummy = new DemoController();
      
          // Configure Web API for self-host. 
          var config = new HttpConfiguration();
          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
      
          app.UseWebApi(config);
      }
      
    8. Compile and run

    9. Install the service with "Project.exe" install

    10. Now you have a windows service "Self Host Web API Demo'