본문 바로가기
개발/.NET

Windows Service 템플릿 없이 Console Application으로 서비스 자동 등록/해제

by 그저그런보통사람 2015. 9. 4.

보통 서비스 모듈을 윈도우 서비스 형태로 서비스하기 위해 별도의 윈도우 서비스 프로젝트를 생성하고, 개발 완료 후 배치나 명령어 (sc create xxxx , net start xxxx) 로 등록한다.


좀 더 쉬운 방법이 있는데, 콘솔 프로젝트에 직접 서비스 클래스를 적용하는 것이다.


이하 코드 참조


class Program : ServiceBase

    {

        static void Main(string[] args)

        {

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;


            if (System.Environment.UserInteractive)

            {

                string parameter = string.Concat(args);


 // console arguments를 이용하여 설치/제거

                switch(parameter)

                {

                    case "--install":

// System.Configuration.Install dll 참조...

                        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });

                        break;

                    case "--uninstall":

                        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location                     });

                        break;

                }

            }

            else

            {

                ServiceBase.Run(new Program());

            }


  // 프로세스가 종료되지 않도록 대기

            Console.ReadKey();

        }


  

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

        {

            File.AppendAllText(@"d:\temp\error.txt", ((Exception)e.ExceptionObject).Message + ((Exception)e.ExceptionObject).InnerException.Message + "\r\n");

        }


        protected override void OnStart(string[] args)

        {

            base.OnStart(args);


            Task.Run(async () => {

                await Task.Delay(5000);

                TestClass tc = new TestClass();

                tc.Start();

            });

        }

    }



    [RunInstaller(true)]

    public class MyWindowsServiceInstaller :Installer

    {

        public MyWindowsServiceInstaller()

        {

            // System.ServiceProcess dll 참조

            var processInstaller = new ServiceProcessInstaller();

            var serviceInstaller = new ServiceInstaller();


            processInstaller.Account = ServiceAccount.LocalService;


            serviceInstaller.DisplayName = "TEST Service";

            serviceInstaller.StartType = ServiceStartMode.Automatic;


            serviceInstaller.ServiceName = "TEST Service";

            this.Installers.Add(processInstaller);

            this.Installers.Add(serviceInstaller);

        }

    }