My question is How can I write the windows service in .net core which we used to write in prior .net versions ?
Lots of links/articles explain how to host your .net
This is one way of building windows services using .net core.
It is built using P/Invoke calls into native windows assemblies.
Example of writing windows service (taken from github project's page):
using DasMulli.Win32.ServiceUtils;
class Program
{
public static void Main(string[] args)
{
var myService = new MyService();
var serviceHost = new Win32ServiceHost(myService);
serviceHost.Run();
}
}
class MyService : IWin32Service
{
public string ServiceName => "Test Service";
public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
{
// Start coolness and return
}
public void Stop()
{
// shut it down again
}
}
It is not perfect but IMHO it is pretty nice.
Not sure if there is a default way of doing this. You can however let your core application inherit from ServiceBase and implement the necessary overrides. We do this in our application (note that we target the full framework, not core). The original idea for this came from the following articles:
Note that these articles still reference DNX (from the .NET Core beta days) - these days your core app will compile to an exe, so you can adjust their examples to cater for that.
This is another simple way to build windows service in .net Core (console app)
Simple library that allows one to host dot net core application as windows services.
Using nuget: Install-Package PeterKottas.DotNetCore.WindowsService
Create your first service, something like this:
public class ExampleService : IMicroService
{
public void Start()
{
Console.WriteLine("I started");
}
public void Stop()
{
Console.WriteLine("I stopped");
}
}
Api for services:
ServiceRunner<ExampleService>.Run(config =>
{
var name = config.GetDefaultName();
config.Service(serviceConfig =>
{
serviceConfig.ServiceFactory((extraArguments) =>
{
return new ExampleService();
});
serviceConfig.OnStart((service, extraArguments) =>
{
Console.WriteLine("Service {0} started", name);
service.Start();
});
serviceConfig.OnStop(service =>
{
Console.WriteLine("Service {0} stopped", name);
service.Stop();
});
serviceConfig.OnError(e =>
{
Console.WriteLine("Service {0} errored with exception : {1}", name, e.Message);});
});
});
Run the service without arguments and it runs like console app.