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?
Add a new console application to your solution
Install NuGet Package Microsoft.Owin.SelfHost
, Microsoft.AspNet.WebApi.OwinSelfHost
and Topshelf
to the your new project
Add a Startup.cs
(see here)
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();
}
}
Add code from Topshelf Section to your Main methode
Add a reference to your existing WebApi Project
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);
}
Compile and run
Install the service with "Project.exe" install
Now you have a windows service "Self Host Web API Demo'