C# 서비스 프로그램 만들기

개요

여러가지 이유로 프로그램을 컴퓨터가 시작되면서 실행해야 하는 경우가 있습니다. 프로그램을  시작 프로그램에 등록해서 실행되도록 할 수 있습니다. 이 방법이 아니고 필요에 따라서 서비스 프로그램으로 제작해야 하는 경우가 있습니다. 이번 포스트에서는 C# 서비스 프로그램 으로 제작하는 방법을 알아보도록 하겠습니다.

서비스 프로그램은 실행파일로 컴파일되도 바로 실행되지 않습니다. 실행하면 다음과 같은 오류가 발생합니다.

서비스 프로그램을 바로 실행한 경우

서비스 프로그램을 바로 실행한 경우

installutil 유틸리티를 이용하여 등록해야 합니다. 이 유틸리티는 다음의 경로에 있습니다. 프롬프트는 관리자 모드로 실행 후 명령을 수행해야 제대로 설치됩니다. 그렇지 않으면 “System.Security.SecurityException: 소스를 찾을 수 없습니다. 일부 또는 전체 이벤트 로그를 검색하지 못했습니다. 액세스할 수 없는 로그: Security.” 이런식의 오류가 발생합니다.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil

다음의 명령으로 등록하면 되고 /u 옵션을 주면 등록을 해제할 수 있습니다.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe C:\경로\서비스프로그램.exe

서비스 프로그램 프로젝트 생성

프로젝트 생성을 선택하고 다음의 Windows 서비스 템플릿을 선택합니다.

Windows 서비스 템플릿 선택

Windows 서비스 템플릿 선택

서비스 프로그램에서 처리할 부분을 작업하고 빌드합니다. 생성된 exe파일을 위의 명령으로 등록해보면 정상적으로 되지 않는 것을 알수 있습니다. “D:\temp\WindowsService1\WindowsService1\bin\Release\WindowsService1.exe 어셈블리에서 RunInstallerAttribute.Yes 특성을 포함하는 공용 설치 관리자를 찾을 수 없습니다.
설치 관리자가 없으므로 InstallState 파일을 제거합니다.” 별도의 설치관련 클래스를 추가해야 합니다.

설치되지 않을때의 메시지

설치되지 않을때의 메시지

설치관련 클래스추가

아래와 같이 클래스를 추가합니다. 여기에서 클래스는 public으로 선언해야 정상적으로 서비스로 설치됩니다.

설치 관리자 클래스 추가

설치 관리자 클래스 추가

클래스를 추가한 후 System.Configuration.Install 어셈블리를 참조 추가합니다.

System.Configuration.Install 어셈블리를 참조 추가

System.Configuration.Install 어셈블리를 참조 추가

다음과 같이 생성자를 추가하고 서비스의 이름과 설명등을 적절하게 입력합니다. RunInstallerAttribute(true) 속성을 추가하고 WindowsServiceInstaller 클래스는 Installer 클래스를 상속하도록 합니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace WindowsService1
{
	[RunInstallerAttribute(true)]
	public class WindowsServiceInstaller: Installer
	{
		public WindowsServiceInstaller()
		{
			var serviceProcessInstaller = new ServiceProcessInstaller();
			var serviceInstaller = new ServiceInstaller();

			serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
			serviceProcessInstaller.Username = null;
			serviceProcessInstaller.Password = null;

			serviceInstaller.Description = "Mail monitoring service";
			serviceInstaller.DisplayName = "Mail monitor";
			serviceInstaller.ServiceName = "Mail monitoring";
			serviceInstaller.StartType = ServiceStartMode.Automatic;

			this.Installers.Add(serviceProcessInstaller);
			this.Installers.Add(serviceInstaller);
		}
	}
}

빌드한 후 위의 등록 명령을 다시 실행하면 정상적으로 등록됨을 알 수 있습니다.

정상적으로 등록된 서비스 프로그램

정상적으로 등록된 서비스 프로그램

이상으로 .NET 기반 C# 으로 서비스 프로그램을 만드는 방법을 알아보았습니다.

 

 

C# 서비스 프로그램 만들기”에 대한 2개의 생각

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

Time limit is exhausted. Please reload the CAPTCHA.