Saturday, January 21, 2023

.Net Core Console Application As Windows Service - Background Activity

We can convert our .Net Core Console Application into regular Windows Service by using third party library like TopShelf, Quartz and for logging  we can utilize NLog.

Windows Service is mainly used when you want a regular running process in the background that do some activity behind the seen. 

Lets try to convert .Net Core Console Application to Windows Service. 


Open Visula Studio 2019 - > Go to New Project -> Select .Net Core(Console) template and Create project

We have to include maily two library

  • Topshelf
  • Quartz

Topshelf

Topshelf is use to initialies HostFactory Like Below

	
        var services = ServiceDependency.ConfigureServices();
        var serviceProvider = services.BuildServiceProvider();

        var rc = HostFactory.Run(x =>
        {
            x.Service(s =>
            {
                s.ConstructUsing(name => serviceProvider.GetService());
                s.WhenStarted(tc => tc.Start());
                s.WhenStopped(tc => tc.Stop());
            });
            x.RunAsLocalSystem();

            x.SetDescription("Windows Service Demo");
            x.SetDisplayName("WinServiceDemo");
            x.SetServiceName("WinServiceDemo");
        });

        var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
        Environment.ExitCode = exitCode;

	

Quartz

Quart Library is used to Schedule services like below

	
           public JobTrigger GetCommonJob()
    {

        ReportProcessorJobKey = JobKey.Create("CommonJob", "CommonJob");

        var job = JobBuilder.Create().WithIdentity("CommonJob", "CommonJob").Build();
        int ConfigFrequency;
        int frequency = int.TryParse(ConfigurationManager.AppSettings["CommonJobFrequencyInSecond"], out ConfigFrequency) ? ConfigFrequency : 5;
        var jobTrigger = TriggerBuilder.Create()
            .WithSimpleSchedule(x => x.WithIntervalInSeconds(frequency).RepeatForever())
            .Build();

        return new JobTrigger { Job = job, Trigger = jobTrigger };
    }

	

For Source Code : You can follow the below Link

The Complete Source Code Example is availabe on below link ..

Download

Popular Articles