Host windows service on server

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.

Читайте также:  How to get ubuntu linux

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.

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.

Что такое Service Host процесс (svchost.exe) и почему их так много?

Е сли Вы когда-нибудь просматривали Диспетчер задач, то, возможно, Вы задавались вопросом, почему запущенно так много Service Host процессов. Вы не можете убить их, и Вы точно не запускали их. Итак, что это?

Что такое Service Host процесс

Вот ответ, согласно Microsoft:

Svchost.exe — это общее имя хоста для служб, которые запускаются из библиотек динамической компоновки.

Но это не очень помогло нам понять что это. Некоторое время назад корпорация Майкрософт начала изменять большую часть функциональности Windows с использования внутренних служб Windows (которые запускались из EXE-файлов) на использование DLL-файлов. С точки зрения программирования это делает код более многоразовым и, возможно, легче поддерживать в актуальном состоянии. Проблема в том, что Вы не можете запускать DLL-файл непосредственно из Windows так же, как и исполняемый файл. Вместо этого оболочка, загружаемая из исполняемого файла, используется для размещения этих DLL-сервисов. Так появился процесс Service Host (svchost.exe).

Почему запущено так много Service Host процессов

Если Вы когда-нибудь просматривали раздел «Службы» в панели управления, то Вы, вероятно, заметили, что Windows требует много сервисов. Если каждая отдельная служба будет работать под одним Service Host процессом, то отказ в одной службе может привести к сбою всей Windows. Поэтому они отделены друг от друга.

Службы организованы в логические группы, которые все связаны друг с другом, а затем создается один экземпляр Service Host процесса для размещения каждой группы. Например, один Service Host процесс запускает три службы, связанные с брандмауэром. Другой Service Host процесс может запускать все службы, связанные с пользовательским интерфейсом, и так далее. На приведенном ниже изображении, например, Вы можете видеть, что один Service Host (узел службы) процесс запускает несколько связанных сетевых служб, а другой запускает службы, связанные с удаленными вызовами процедур.

Что мне делать со всей этой информацией?

Честно говоря, не так много. Во времена Windows XP (и предыдущих версий), когда на компьютерах было гораздо больше ограниченных ресурсов и операционные системы не были столь тонко настроены, часто рекомендовалось останавливать Windows от запуска ненужных служб. Теперь мы больше не рекомендуем отключать службы. Современные ПК, как правило, обладают большой памятью и мощными процессорами. Добавьте к этому тот факт, что способ обработки Windows-служб в современных версиях (в том числе и запущенных) был оптимизирован, и отключение служб, которые, по Вашему мнению, Вам не нужны, действительно не имеют большого влияния.

Тем не менее, если Вы заметили, что конкретный экземпляр Service Host или связанная с ним служба вызывает проблемы, такие как постоянное чрезмерное использование процессора или ОЗУ, то Вы можете проверить сервисы, которые задействованы. Это может по крайней мере дать Вам представление о том, где начать поиск и устранение неисправностей. Существует несколько способов узнать, какие службы содержатся в определенном экземпляре Service Host. Вы можете посмотреть это в диспетчере задач или использовать отличное стороннее приложение под названием Process Explorer.

Проверка связанных служб в диспетчере задач

Если вы используете Windows 8 или 10, процессы отображаются на вкладке «Процессы» диспетчера задач. Если процесс служит хостом для нескольких служб, то Вы можете увидеть эти службы, просто развернув процесс. Это позволит легко определить, какие службы относятся к каждому экземпляру Service Host процесса.


Вы можете щелкнуть правой кнопкой мыши по любой отдельной службе, чтобы остановить службу, просмотреть ее в приложении «Службы» или даже выполнить поиск в Интернете для получения информации о службе.


Если Вы используете Windows 7, то все немного по-другому. Диспетчер задач Windows 7 не группирует процессы таким же образом и не отображает обычные имена процессов — он показывает только все экземпляры «svchost.exe». Нужно немного больше действий, чтобы определить службы, связанные с конкретным экземпляром «svchost.exe».

На вкладке «Процессы» диспетчера задач в Windows 7 щелкните правой кнопкой мыши по определенному процессу «svchost.exe», а затем выберите вариант «Перейти к службам».


Это действие перенаправит Вас на вкладку «Службы», где все службы, запущенные под процессом «svchost.exe», будут выбраны.


Затем Вы можете увидеть полное имя каждой службы в столбце «Описание», чтобы можно было отключить эту службу, если Вы не хотите ее запускать или устранить неполадки, если они возникают.

Проверка связанных сервисов с помощью Process Explorer

Microsoft также предоставляет отличный инструмент для работы с процессами в составе линейки Sysinternals. Просто загрузите Process Explorer и запустите его — это портативное приложение, поэтому нет необходимости его устанавливать.

Для наших целей, однако, Process Explorer группирует связанные службы в каждом экземпляре «svchost.exe». Они перечислены по именам файлов, но их полные имена также отображаются в столбце «Описание». Вы также можете навести указатель мыши на любой из процессов «svchost.exe», чтобы увидеть всплывающее окно со всеми службами, связанными с этим процессом, — даже теми, которые в настоящее время не выполняются.

Может ли этот процесс быть вирусом?

Сам процесс является официальным компонентом Windows. Возможно, что вирус заменил реальный Service Host собственным исполняемым файлом, что очень маловероятно. Если Вы хотите быть уверенным, то можете проверить расположение файла процесса. В диспетчере задач щелкните правой кнопкой мыши на любом Service Host процессе и выберите опцию «Открыть расположение файла».


Если файл хранится в папке Windows\System32, то можете быть уверены, что это не вирус.


Тем не менее, если Вы хотите быть спокойным, то Вы всегда можете просканировать систему на вирусы с помощью антивирусного сканера.

Читайте также:  Pci ven 8086 dev a12f cc 0c03 драйвер windows 10 64
Оцените статью