Windows service или wcf

Практическое руководство. Размещение службы WCF в управляемой службе Windows How to: Host a WCF Service in a Managed Windows Service

В этом разделе описаны основные шаги, необходимые для создания службы Windows Communication Foundation (WCF), размещенной в службе Windows. This topic outlines the basic steps required to create a Windows Communication Foundation (WCF) service that is hosted by a Windows Service. Сценарий включается параметром размещения управляемой службы Windows, который является длительно запущенной службой WCF, размещенной вне службы IIS (IIS) в безопасной среде, которая не является активируемой для сообщения. The scenario is enabled by the managed Windows service hosting option that is a long-running WCF service hosted outside of Internet Information Services (IIS) in a secure environment that is not message activated. Вместо этого время существования службы контролируется операционной системой. The lifetime of the service is controlled instead by the operating system. Данный вариант размещения доступен во всех версиях Windows. This hosting option is available in all versions of Windows.

Службами Windows можно управлять при помощи Microsoft.ManagementConsole.SnapIn в консоли управления (MMC) и можно настроить их автоматический запуск при загрузке системы. Windows services can be managed with the Microsoft.ManagementConsole.SnapIn in Microsoft Management Console (MMC) and can be configured to start up automatically when the system boots up. Этот вариант размещения состоит из регистрации домена приложения (AppDomain), в котором размещена служба WCF, в качестве управляемой службы Windows, чтобы время существования процесса службы управлялось диспетчером управления службами (SCM) для служб Windows. This hosting option consists of registering the application domain (AppDomain) that hosts a WCF service as a managed Windows service so that the process lifetime of the service is controlled by the Service Control Manager (SCM) for Windows services.

Код службы включает в себя реализацию службы контракта службы, класс службы Windows и класс установщика. The service code includes a service implementation of the service contract, a Windows Service class, and an installer class. Класс реализации службы, CalculatorService , — это служба WCF. The service implementation class, CalculatorService , is a WCF service. Класс CalculatorWindowsService является службой Windows. The CalculatorWindowsService is a Windows service. Чтобы считаться службой Windows, этот класс наследует от класса ServiceBase и реализует методы OnStart и OnStop . To qualify as a Windows service, the class inherits from ServiceBase and implements the OnStart and OnStop methods. В методе OnStart создается объект ServiceHost для типа CalculatorService и открывается. In OnStart , a ServiceHost is created for the CalculatorService type and opened. В методе OnStop служба останавливается и освобождается. In OnStop , the service is stopped and disposed. Ведущее приложение также отвечает за предоставление базового адреса для узла службы, настроенного в параметрах приложения. The host is also responsible for providing a base address to the service host, which has been configured in application settings. Класс установщика, унаследованный от класса Installer, позволяет выполнить установку программы как службы Windows с помощью Installutil.exe. The installer class, which inherits from Installer, allows the program to be installed as a Windows service by the Installutil.exe tool.

Создание службы и предоставление кода размещения Construct the service and provide the hosting code

Создайте новый проект консольного приложения Visual Studio с именем Service. Create a new Visual Studio Console app project called Service.

Измените имя файла Program.cs на Service.cs. Rename Program.cs to Service.cs.

Измените пространство имен на Microsoft.ServiceModel.Samples . Change the namespace to Microsoft.ServiceModel.Samples .

Добавьте ссылки на следующие сборки: Add references to the following assemblies:

Добавьте следующие операторы using в файл Service.cs. Add the following using statements to Service.cs.

Определите контракт службы ICalculator , как показано в следующем коде. Define the ICalculator service contract as shown in the following code.

Читайте также:  Как изменить настройки рабочего стола windows

Реализуйте контракт службы в классе с именем CalculatorService , как показано в следующем коде. Implement the service contract in a class called CalculatorService as shown in the following code.

Создайте новый класс с именем CalculatorWindowsService , производный от класса ServiceBase. Create a new class called CalculatorWindowsService that inherits from the ServiceBase class. Добавьте локальную переменную с именем serviceHost , чтобы создать ссылку на экземпляр ServiceHost. Add a local variable called serviceHost to reference the ServiceHost instance. Определите метод Main , который вызывает ServiceBase.Run(new CalculatorWindowsService) . Define the Main method that calls ServiceBase.Run(new CalculatorWindowsService)

Переопределите метод OnStart(String[]), создав и открыв новый экземпляр ServiceHost, как показано в следующем коде. Override the OnStart(String[]) method by creating and opening a new ServiceHost instance as shown in the following code.

Переопределите метод OnStop, закрывающий ServiceHost, как показано в следующем коде. Override the OnStop method closing the ServiceHost as shown in the following code.

Создайте новый класс с именем ProjectInstaller , производный от Installer и помеченный атрибутом RunInstallerAttribute, установленным в значение true . Create a new class called ProjectInstaller that inherits from Installer and that is marked with the RunInstallerAttribute set to true . Это позволяет устанавливать службу Windows программой Installutil.exe. This allows the Windows service to be installed by the Installutil.exe tool.

Удалите класс Service , созданный при создании проекта. Remove the Service class that was generated when you created the project.

Добавьте в проект файл конфигурации приложения. Add an application configuration file to the project. Замените содержимое этого файла следующим XML-кодом конфигурации. Replace the contents of the file with the following configuration XML.

Щелкните правой кнопкой мыши файл App.config в Обозреватель решений и выберите пункт свойства. Right click the App.config file in the Solution Explorer and select Properties. В разделе Копировать в выходной каталог выберите Копировать, если новее. Under Copy to Output Directory select Copy if Newer.

В этом примере конечные точки явно задаются в файле конфигурации. This example explicitly specifies endpoints in the configuration file. Если в службу не добавлена ни одна конечная точка, то среда выполнения добавляет конечные точки по умолчанию. If you do not add any endpoints to the service, the runtime adds default endpoints for you. В этом примере, поскольку для службы параметр ServiceMetadataBehavior установлен в значение true , в ней также будет включена публикация метаданных. In this example, because the service has a ServiceMetadataBehavior set to true , your service also has publishing metadata enabled. Дополнительные сведения о конечных точках по умолчанию, привязках и режимах работы см. в разделах Упрощенная конфигурация и Упрощенная конфигурация служб WCF. For more information about default endpoints, bindings, and behaviors, see Simplified Configuration and Simplified Configuration for WCF Services.

Установка и запуск службы Install and run the service

Постройте решение, чтобы создать исполняемый файл Service.exe . Build the solution to create the Service.exe executable.

Откройте Командная строка разработчика для Visual Studio и перейдите в каталог проекта. Open Developer Command Prompt for Visual Studio and navigate to the project directory. В командной строке введите installutil bin\service.exe , чтобы установить службу Windows. Type installutil bin\service.exe at the command prompt to install the Windows service.

В командной строке введите services.msc , чтобы получить доступ к диспетчеру служб. Type services.msc at the command prompt to access the Service Control Manager (SCM). Служба Windows должна появиться в списке служб с именем WCFWindowsServiceSample. The Windows service should appear in Services as «WCFWindowsServiceSample». Служба WCF может отвечать только на клиенты, если запущена служба Windows. The WCF service can only respond to clients if the Windows service is running. Чтобы запустить службу, щелкните ее правой кнопкой мыши в SCM и выберите «запустить» или введите net start WCFWindowsServiceSample в командной строке. To start the service, right-click it in the SCM and select «Start», or type net start WCFWindowsServiceSample at the command prompt.

Чтобы внести изменения в службу, необходимо предварительно остановить ее и удалить. If you make changes to the service, you must first stop it and uninstall it. Чтобы отключить службу, щелкните правой кнопкой мыши службу в SCM и выберите пункт «Закрыть» или введите команду net Service WCFWindowsServiceSample в командной строке. To stop the service, right-click the service in the SCM and select «Stop», or type net stop WCFWindowsServiceSample at the command prompt. Учтите, что если остановить службу Windows, а затем запустить клиент, то когда клиент попытается обратиться к службе, будет вызвано исключение EndpointNotFoundException. Note that if you stop the Windows service and then run a client, an EndpointNotFoundException exception occurs when a client attempts to access the service. Чтобы удалить службу Windows, введите в командной строке команду installutil/u bin\service.exe . To uninstall the Windows service type installutil /u bin\service.exe at the command prompt.

Читайте также:  Windows print document to file

Пример Example

Ниже приведен полный список кода, используемого в этом разделе. The following is a complete listing of the code used by this topic:

Как и в случае резидентного размещения, среда размещения службы Windows требует, чтобы код размещения являлся частью приложения. Like the «Self-Hosting» option, the Windows service hosting environment requires that some hosting code be written as part of the application. Служба реализуется как консольное приложение и содержит собственный код размещения. The service is implemented as a console application and contains its own hosting code. В других средах размещения, таких как служба активации Windows (WAS), размещающих в IIS, писать код размещения необязательно. In other hosting environments, such as Windows Process Activation Service (WAS) hosting in Internet Information Services (IIS), it is not necessary for developers to write hosting code.

Размещение в приложении службы Windows Hosting in a Windows Service Application

Службы Windows (ранее называвшиеся службами Windows NT) обеспечивают модель процессов, особенно подходящую для приложений, которые должны существовать в длительно исполняемом файле и не отображают никакой формы пользовательского интерфейса. Windows services (formerly known as Windows NT services) provide a process model particularly suited to applications that must live in a long-running executable and do not display any form of user interface. Временем существования процессов приложений служб Windows управляет диспетчер служб, который позволяет запускать, останавливать и приостанавливать приложения служб Windows. The process lifetime of a Windows service application is managed by the service control manager (SCM), which allows you to start, stop, and pause Windows service applications. Можно настроить автоматический запуск процесса службы Windows при запуске компьютера, сделав его подходящей средой размещения для приложений Always on. You can configure a Windows service process to start automatically when the computer starts, making it a suitable hosting environment for «always on» applications. Дополнительные сведения о приложениях служб Windows см. в разделе приложения службы Windows. For more information about Windows service applications, see Windows Service Applications.

Приложения, на которых размещаются длительные службы Windows Communication Foundation (WCF), совместно используют многие характеристики со службами Windows. Applications that host long-running Windows Communication Foundation (WCF) services share many characteristics with Windows services. В частности, службы WCF — это длительно выполняемые серверные исполняемые файлы, которые не взаимодействуют напрямую с пользователем и поэтому не реализуют какой-либо формы пользовательского интерфейса. In particular, WCF services are long-running server executables that do not interact directly with the user and therefore do not implement any form of user interface. Таким образом, размещение служб WCF внутри приложения службы Windows — один вариант для создания надежных, долгосрочных приложений WCF. As such, hosting WCF services inside of a Windows service application is one option for building robust, long-running, WCF applications.

Часто разработчики WCF должны решить, следует ли размещать свое приложение WCF в приложении службы Windows или в среде размещения служб службы IIS (IIS) или службы активации Windows (WAS). Often, WCF developers must decide whether to host their WCF application inside of a Windows service application or inside of the Internet Information Services (IIS) or Windows Process Activation Service (WAS) hosting environment. Рассмотреть возможность использования приложений служб Windows необходимо в следующих случаях. You should consider using Windows service applications under the following conditions:

Приложение требует явной активации. Your application requires explicit activation. Например, службы Windows следует использовать, когда приложение должно запускаться автоматически при запуске сервера, а не динамически при поступлении первого входящего сообщения. For example, you should use Windows services when your application must start automatically when the server starts instead of being dynamically started in response to the first incoming message.

Читайте также:  Setting windows system path

Процесс, в котором размещается приложение, после запуска должен оставаться работающим. The process that hosts your application must remain running once started. После запуска процесс службы Windows остается работающим, если явно не завершается администратором сервера с помощью диспетчера служб. Once started, a Windows service process remains running unless explicitly shut down by a server administrator using the service control manager. Приложения, размещенные в IIS или службе активации Windows, могут запускаться и останавливаться динамически для обеспечения оптимального использования системных ресурсов. Applications hosted in IIS or WAS may be started and stopped dynamically to make optimal use of system resources. Приложения, для которых требуется явное управление в течение времени существования их процесса размещения, должны использовать службы Windows, а не IIS или службу активации Windows. Applications that require explicit control over the lifetime of their hosting process should use Windows services instead of IIS or WAS.

Служба WCF должна работать на Windows Server 2003 и использовать транспорты, отличные от HTTP. Your WCF service must run on Windows Server 2003 and use transports other than HTTP. В Windows Server 2003 среда размещения IIS 6,0 ограничена только связью по протоколу HTTP. On Windows Server 2003, the IIS 6.0 hosting environment is restricted to HTTP communication only. Это ограничение не распространяется на приложения служб Windows и может использовать любой поддерживаемый транспортный протокол WCF, включая NET. TCP, net. pipe и net. MSMQ. Windows service applications are not subject to this restriction and can use any transport WCF supports, including net.tcp, net.pipe, and net.msmq.

Размещение WCF в приложении службы Windows To host WCF inside of a Windows service application

Создайте приложение службы Windows. Create a Windows service application. Приложения служб Windows можно создавать в управляемом коде, используя классы в пространстве имен System.ServiceProcess. You can write Windows service applications in managed code using the classes in the System.ServiceProcess namespace. Это приложение должно включать один класс, наследуемый от ServiceBase. This application must include one class that inherits from ServiceBase.

Свяжите время существования служб WCF со временем существования приложения службы Windows. Link the lifetime of the WCF services to the lifetime of the Windows service application. Как правило, службы WCF, размещенные в приложении службы Windows, становятся активными при запуске службы размещения, прекращают прослушивание сообщений при остановке службы размещения и завершают процесс размещения, когда служба WCF обнаруживает ошибку. Typically, you want WCF services hosted in a Windows service application to become active when the hosting service starts, stop listening for messages when the hosting service is stopped, and shut down the hosting process when the WCF service encounters an error. Это можно обеспечить, выполнив следующие действия. This can be accomplished as follows:

Переопределите OnStart(String[]), чтобы открыть один или несколько экземпляров ServiceHost. Override OnStart(String[]) to open one or more instances of ServiceHost. Одно приложение службы Windows может размещать несколько служб WCF, запускаемых и останавливаемых в качестве группы. A single Windows service application can host multiple WCF services that start and stop as a group.

Переопределите OnStop для вызова Closed на ServiceHost всех запущенных службах WCF, которые были запущены во время OnStart(String[]) . Override OnStop to call Closed on the ServiceHost any running WCF services that were started during OnStart(String[]).

Подпишитесь на событие Faulted приложения ServiceHost и используйте класс ServiceController, чтобы завершить работу приложения службы Windows в случае ошибки. Subscribe to the Faulted event of ServiceHost and use the ServiceController class to shut down the Windows service application in case of error.

Приложения служб Windows, в которых размещаются службы WCF, развертываются и управляются так же, как приложения служб Windows, которые не используют WCF. Windows service applications that host WCF services are deployed and managed in the same way as Windows service applications that do not make use of WCF.

Оцените статью