[C# NuGet] Topshelf 이란?

참조


소개

  • Topshelf는 .NET을 사용하여 Windows 서비스를 구축하기 위한 쉬운 서비스 호스팅 프레임워크입니다.
  • 서비스 생성이 단순화되어 개발자가 Topshelf를 사용하여 서비스로 설치할 수 있는 간단한 콘솔 응용 프로그램을 만들 수 있습니다.
  • 그 이유는 간단합니다.
  • 서비스보다 콘솔 애플리케이션을 디버그하는 것이 훨신 쉽기 때문입니다.
  • 애플리케이션이 테스트되고 프로덕션 준비가 되면 Topshelf를 사용하여 애플리케이션을 서비스로 쉽게 설치할 수 있습니다.

Topshelf 설치

  • C# 에서 Topshelf 를 쉽게 설치하는 방법은 Visual Studio에서 NuGet Package 를 설치하면 됩니다.
  • 도구->NuGet 패키지 관리자-> 솔루션용 NuGet 패키지 관리에서 Topshelf NuGet을 검색 후, 설치 진행합니다.


Topshelf 예제

  • 설치를 모두 완료 하였다면, C# 에서 Topshelf 사용 예제 코드를 작성해 보도록 하겠습니다.
  • TownCrier 클래스를 선언 후, Timer 객체를 선언하여 1초마다 한번씩 CMD 창에 해당 시간이 출력되도록 하는 콘솔 프로그램이 있습니다.
  • 해당 프로그램을 Topshelf을 통해 실행해 보도록 하겠습니다.
using System;
using System.Timers;
using Topshelf;
using Topshelf.HostConfigurators;

namespace interfaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Execute();
        }

        public static void Execute()
        {
            HostFactory.Run(hc =>
            {
                SetService(hc);
                SetServiceName(hc);
            });
        }

        private static void SetService(HostConfigurator hc)
        {
            hc.Service<TownCrier>(sc =>
            {
                sc.ConstructUsing(name => new TownCrier());
                sc.WhenStarted(tc => tc.Start());
                sc.WhenStopped(tc => tc.Stop());
            });
        }

        private static void SetServiceName(HostConfigurator hc)
        {
            hc.SetDescription("Sample Topshelf Host");
            hc.SetDisplayName("Stuff");
            hc.SetServiceName("Stuff");
        }
    }

    public class TownCrier
    {
        readonly Timer _timer;
        public TownCrier()
        {
            _timer = new Timer(1000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
        }
        public void Start() { _timer.Start(); }
        public void Stop() { _timer.Stop(); }
    }
}

실행 결과

  • 실행 결과, 서비스가 정상적으로 실행되어 동작되는 것을 확인할 수 있습니다.
Configuration Result:
[Success] Name Stuff
[Success] Description Sample Topshelf Host
[Success] ServiceName Stuff
Topshelf v4.3.0.0, .NET 5.0.13 (5.0.13)
The Stuff service is now running, press Control+C to exit.
It is 2022-01-11 오후 7:31:43 and all is well
It is 2022-01-11 오후 7:31:44 and all is well
It is 2022-01-11 오후 7:31:45 and all is well
It is 2022-01-11 오후 7:31:46 and all is well
It is 2022-01-11 오후 7:31:47 and all is well
It is 2022-01-11 오후 7:31:48 and all is well
It is 2022-01-11 오후 7:31:49 and all is well
It is 2022-01-11 오후 7:31:50 and all is well
It is 2022-01-11 오후 7:31:51 and all is well
It is 2022-01-11 오후 7:31:52 and all is well
It is 2022-01-11 오후 7:31:53 and all is well
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY