How To Create Window Service In .Net Core

Agenda

  • Introduction
  • Step-by-step Implementation

Prerequisites

  • .NET Core 6 SDK
  • Visual Studio 2022
  • SQL Server

Introduction

In this article, we will learn how to create a window service with dot net core web APIs help of  Microsoft.Extension.Hosting and Microsoft.Extension.Hosting.WindowService.

Step-By-Step Implementation

Step 1. We are creating a project with the .Net Core Worker Service Template

New Project

Step 2. Add Project With Name Is DataLayer Its Work As Database communication.

Configure project

Additional information

The Solution looks like below.

Datalayer

Step 3. Next, we install the Package used for SQL Database connection for the DataLayer Project.

  1. Microsoft.EntityFrameworkCore.SqlServer 
  2. Microsoft.EntityFrameworkCore.Tools 
  3. Microsoft.EntityFrameworkCore 
  4. Microsoft.EntityFrameworkCore.Design 

Nuget Datalayer

Step 4. Next, we are installing the Package used for Window Services for the Main Project with the name User Status Update.

  1. Microsoft.Extension.Hosting 
  2. Microsoft.Extension.Hosting.WindowService

Status update

Step 5. Next, we add Project reference into the Main Project (User Status Update) used for DataLayer Functions

 

Step 6. Next, we create a Table with the name is User to store User Information and Select All Records

SQL Query

Step 7. Next, we create a Stored procedure with the name (UserStatusUpdate) used to Update the Status of the User Table. 

Step 8. The scaffold-DbContext command is used to generate code for Context and Entity Type for the Database.

Database

Step 9. We see Auto Generate Db Context File.

E-Commerce Context

Step 10. Next, we add a User Repository Class used to call stored procedures and update the Status of the User Based on Logic.

C# items

User repository

IUserRepository.cs Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace User_Status_Update.Repository
{
    public interface IUserRepository
    {
        void UserStatusUpdate();
    }
}

UserRepository.cs Class

using DataLayer.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace User_Status_Update.Repository
{
    public class UserRepository : IUserRepository
    {
        private readonly EcommerceContext _context;

        public UserRepository(EcommerceContext _context)
        {
            this._context = _context;
        }

        public void UserStatusUpdate()
        {
            this._context.Database.ExecuteSqlRaw("EXEC UserStatusUpdate");
        }
    }
}

Program.cs class



using DataLayer.Data;
using Microsoft.EntityFrameworkCore;
using User_Status_Update;
using User_Status_Update.Repository;

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json").Build();

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureServices(services =>
    {
        services.AddDbContext<EcommerceContext>(opt=>
        {
            opt.UseSqlServer(configuration.GetConnectionString("Db"));
        });
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddHostedService<UserService>();
    })
    .Build();

await host.RunAsync();

UserService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using User_Status_Update.Repository;

namespace User_Status_Update
{
    public class UserService : BackgroundService
    {
        private readonly IUserRepository userRepository;

        public UserService(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {

                await Task.Run(() =>
                {
                    Thread.Sleep(1000 * 60);
                    this.userRepository.UserStatusUpdate();
                });
            }            
        }
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}

Step 11. Let's Right click on Project and select publish and from the publish target list choose the target method as file system and click on Save.

Folder

Location

Publish

Finish

Next, we will Publish the project as User Status Update.exe file path.

Files

Step 12. Open the command prompt as an administrator, write the command look below.

CMD 

Step 13. Here you go, TestUserService Installed successfully.

Command

Step 14. Select TestUserService and click start to start service; go to TestUserService.exe after every minute to update the User Status.

Services

To Change Status with 2.


Similar Articles