Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing windows service in .net core

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 core application as windows service. So this is the only way I can create windows service ?

If yes, can anyone please provide the links/example of it

Thanks !

like image 710
XamDev Avatar asked Nov 23 '16 11:11

XamDev


People also ask

Can we create Windows Service in .NET Core?

NET Core and . NET 5+, developers who relied on . NET Framework could create Windows Services to perform background tasks or execute long-running processes. This functionality is still available and you can create Worker Services that run as a Windows Service.


1 Answers

This is another simple way to build windows service in .net Core (console app)

DotNetCore.WindowsService

Simple library that allows one to host dot net core application as windows services.

Installation

Using nuget: Install-Package PeterKottas.DotNetCore.WindowsService

Usage

  1. Create .NETCore console app.
  2. 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");
        }
    }  
    
  3. 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);});
        });
    });
    
  4. Run the service without arguments and it runs like console app.

  5. Run the service with action:install and it will install the service.
  6. Run the service with action:uninstall and it will uninstall the service.
  7. Run the service with action:start and it will start the service.
  8. Run the service with action:stop and it will stop the service.
like image 153
Soren Avatar answered Sep 26 '22 08:09

Soren