Hosting windows service application

Hosting services

To become active, a service must be hosted within a run-time environment that creates it and controls its context and lifetime. Windows Communication Foundation (WCF) services are designed to run in any Windows process that supports managed code.

WCF provides a unified programming model for building service-oriented applications. This programming model remains consistent and is independent of the run-time environment in which the service is deployed. In practice, this means that the code for your services looks much the same whatever the hosting option.

These hosting options range from running inside a console application to server environments such as a Windows service running within a worker process managed by Internet Information Services (IIS) or by Windows Process Activation Service (WAS). Developers choose the hosting environment that satisfies the service’s deployment requirements. These requirements might derive from the platform on which the application is deployed, the transport on which it must send and receive messages, or on the type of process recycling and other process management required to ensure adequate availability, or on some other management or reliability requirements. The next section provides information and guidance on hosting options.

Hosting options

Self-Host in a Managed Application

WCF services can be hosted in any managed application. This is the most flexible option because it requires the least infrastructure to deploy. You embed the code for the service inside the managed application code and then create and open an instance of the ServiceHost to make the service available. For more information, see How to: Host a WCF Service in a Managed Application.

This option enables two common scenarios: WCF services running inside console applications and rich client applications such as those based on Windows Presentation Foundation (WPF) or Windows Forms (WinForms). Hosting a WCF service inside a console application is typically useful during the application’s development phase. This makes them easy to debug, easy to get trace information from to find out what is happening inside of the application, and easy to move around by copying them to new locations. This hosting option also makes it easy for rich client applications, such as WPF and WinForms applications, to communicate with the outside world. For example, a peer-to-peer collaboration client that uses WPF for its user interface and also hosts a WCF service that allows other clients to connect to it and share information.

Managed Windows Services

This hosting option consists of registering the application domain (AppDomain) that hosts a WCF service as a managed Windows Service (formerly known as NT service) so that the process lifetime of the service is controlled by the service control manager (SCM) for Windows services. Like the self-hosting option, this type of hosting environment requires that some hosting code is written as part of the application. The service is implemented as both a Windows Service and as a WCF service by causing it to inherit from the ServiceBase class as well as from a WCF service contract interface. The ServiceHost is then created and opened within an overridden OnStart(String[]) method and closed within an overridden OnStop() method. An installer class that inherits from Installer must also be implemented to allow the program to be installed as a Windows Service by the Installutil.exe tool. For more information, see How to: Host a WCF Service in a Managed Windows Service. The scenario enabled by the managed Windows Service hosting option is that of a long-running WCF service hosted outside of IIS in a secure environment that is not message-activated. The lifetime of the service is controlled instead by the operating system. This hosting option is available in all versions of Windows.

Internet Information Services (IIS)

The IIS hosting option is integrated with ASP.NET and uses the features these technologies offer, such as process recycling, idle shutdown, process health monitoring, and message-based activation. On the Windows XP and Windows Server 2003 operating systems, this is the preferred solution for hosting Web service applications that must be highly available and highly scalable. IIS also offers the integrated manageability that customers expect from an enterprise-class server product. This hosting option requires that IIS be properly configured, but it does not require that any hosting code be written as part of the application. For more information about how to configure IIS hosting for a WCF service, see How to: Host a WCF Service in IIS.

Читайте также:  Windows temp что за файлы

IIS-hosted services can only use the HTTP transport. Its implementation in IIS 5.1 has introduced some limitations in Windows XP. The message-based activation provided for a WCF service by IIS 5.1 on Windows XP blocks any other self-hosted WCF service on the same computer from using port 80 to communicate. WCF services can run in the same AppDomain/Application Pool/Worker Process as other applications when hosted by IIS 6.0 on Windows Server 2003. But because WCF and IIS 6.0 both use the kernel-mode HTTP stack (HTTP.sys), IIS 6.0 can share port 80 with other self-hosted WCF services running on the same machine, unlike IIS 5.1.

Windows Process Activation Service (WAS)

Windows Process Activation Service (WAS) is the new process activation mechanism for the Windows Server 2008 that is also available on Windows Vista. It retains the familiar IIS 6.0 process model (application pools and message-based process activation) and hosting features (such as rapid failure protection, health monitoring, and recycling), but it removes the dependency on HTTP from the activation architecture. IIS 7.0 uses WAS to accomplish message-based activation over HTTP. Additional WCF components also plug into WAS to provide message-based activation over the other protocols that WCF supports, such as TCP, MSMQ, and named pipes. This allows applications that use communication protocols to use the IIS features such as process recycling, rapid fail protection, and the common configuration system that were only available to HTTP-based applications.

This hosting option requires that WAS be properly configured, but it does not require you to write any hosting code as part of the application. For more information about how to configure WAS hosting, see How to: Host a WCF Service in WAS.

Choose a Hosting Environment

The following table summarizes some of the key benefits and scenarios associated with each of the hosting options.

Hosting Environment Common Scenarios Key Benefits and Limitations
Managed Application («Self-Hosted») — Console applications used during development.
— Rich WinForm and WPF client applications accessing services.
— Flexible.
— Easy to deploy.
— Not an enterprise solution for services.
Windows Services (formerly known as NT services) — A long-running WCF service hosted outside of IIS. — Service process lifetime controlled by the operating system, not message-activated.
— Supported by all versions of Windows.
— Secure environment.
IIS 5.1, IIS 6.0 — Running a WCF service side-by-side with ASP.NET content on the Internet using the HTTP protocol. — Process recycling.
— Idle shutdown.
— Process health monitoring.
— Message-based activation.
— HTTP only.
Windows Process Activation Service (WAS) — Running a WCF service without installing IIS on the Internet using various transport protocols. — IIS is not required.
— Process recycling.
— Idle shutdown.
— Process health monitoring.
— Message-based activation.
— Works with HTTP, TCP, named pipes, and MSMQ.
IIS 7.0 — Running a WCF service with ASP.NET content.
— Running a WCF service on the Internet using various transport protocols.
— WAS benefits.
— Integrated with ASP.NET and IIS content.

The choice of a hosting environment depends on the version of Windows on which it is deployed, the transports it requires to send messages and the type of process and application domain recycling it requires. The following table summarizes the data related to these requirements.

Hosting Environment Platform Availability Transports Supported Process and AppDomain Recycling
Managed Applications («Self-Hosted») Windows XP, Windows Server 2003, Windows Vista,

Windows Server 2008

HTTP,

net.msmq

No
Windows Services (formerly known as NT services) Windows XP, Windows Server 2003, Windows Vista,

Windows Server 2008

HTTP,

net.msmq

No
IIS 5.1 Windows XP HTTP Yes
IIS 6.0 Windows Server 2003 HTTP Yes
Windows Process Activation Service (WAS) Windows Vista, Windows Server 2008 HTTP,

net.msmq

Yes

It is important to note that running a service or any extension from an untrusted host compromises security. Also, when opening a ServiceHost under impersonation, an application must ensure that the user is not logged off, for example by caching the WindowsIdentity of the user.

Hosting in a Windows Service Application

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. 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. You can configure a Windows service process to start automatically when the computer starts, making it a suitable hosting environment for «always on» applications. For more information about Windows service applications, see Windows Service Applications.

Applications that host long-running Windows Communication Foundation (WCF) services share many characteristics with Windows services. 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. As such, hosting WCF services inside of a Windows service application is one option for building robust, long-running, WCF applications.

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. You should consider using Windows service applications under the following conditions:

Your application requires explicit activation. 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.

The process that hosts your application must remain running once started. Once started, a Windows service process remains running unless explicitly shut down by a server administrator using the service control manager. Applications hosted in IIS or WAS may be started and stopped dynamically to make optimal use of system resources. Applications that require explicit control over the lifetime of their hosting process should use Windows services instead of IIS or WAS.

Your WCF service must run on Windows Server 2003 and use transports other than HTTP. On Windows Server 2003, the IIS 6.0 hosting environment is restricted to HTTP communication only. Windows service applications are not subject to this restriction and can use any transport WCF supports, including net.tcp, net.pipe, and net.msmq.

To host WCF inside of a Windows service application

Create a Windows service application. You can write Windows service applications in managed code using the classes in the System.ServiceProcess namespace. This application must include one class that inherits from ServiceBase.

Link the lifetime of the WCF services to the lifetime of the Windows service application. 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:

Override OnStart(String[]) to open one or more instances of ServiceHost. A single Windows service application can host multiple WCF services that start and stop as a group.

Override OnStop to call Closed on the ServiceHost any running WCF services that were started during OnStart(String[]).

Subscribe to the Faulted event of ServiceHost and use the ServiceController class to shut down the Windows service application in case of error.

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.

Размещение в приложении службы 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.

Процесс, в котором размещается приложение, после запуска должен оставаться работающим. 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.

Читайте также:  Количество сессий rdp windows server 2012
Оцените статью