Wcf with windows service

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

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

Читайте также:  Mac os catalina iso vmware

В этом примере конечные точки явно задаются в файле конфигурации. 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.

Пример 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 Communication Foundation Tutorial: Host and run a basic Windows Communication Foundation service

В этом руководстве описывается третья из пяти задач, необходимых для создания приложения Basic Windows Communication Foundation (WCF). This tutorial describes the third of five tasks required to create a basic Windows Communication Foundation (WCF) application. Общие сведения о учебниках см. в разделе учебник. Начало работы с Windows Communication Foundation приложениями. For an overview of the tutorials, see Tutorial: Get started with Windows Communication Foundation applications.

Следующей задачей для создания приложения WCF является размещение службы WCF в консольном приложении. The next task for creating a WCF application is to host a WCF service in a console application. Служба WCF предоставляет одну или несколько конечных точек, каждая из которых предоставляет одну или несколько операций службы. A WCF service exposes one or more endpoints, each of which exposes one or more service operations. Конечная точка службы задает следующие сведения: A service endpoint specifies the following information:

  • Адрес, по которому можно найти службу. An address where you can find the service.
  • Привязка, которая содержит сведения, описывающие, как клиент должен взаимодействовать со службой. A binding that contains the information that describes how a client must communicate with the service.
  • Контракт, определяющий функциональные возможности, предоставляемые службой своим клиентам. A contract that defines the functionality that the service provides to its clients.

В этом руководстве вы узнаете, как: In this tutorial, you learn how to:

  • Создание и Настройка проекта консольного приложения для размещения службы WCF. Create and configure a console app project for hosting a WCF service.
  • Добавьте код для размещения службы WCF. Add code to host the WCF service.
  • Обновите файл конфигурации. Update the configuration file.
  • Запустите службу WCF и убедитесь, что она запущена. Start the WCF service and verify it’s running.

Создание и Настройка проекта консольного приложения для размещения службы Create and configure a console app project for hosting the service

Создание проекта консольного приложения в Visual Studio: Create a console app project in Visual Studio:

Читайте также:  Geforce 6150 windows 10 driver

В меню файл выберите команду Открыть > проект или решение и перейдите к созданному ранее решению GettingStarted (GettingStarted. sln). From the File menu, select Open > Project/Solution and browse to the GettingStarted solution you previously created (GettingStarted.sln). Щелкните Open(Открыть). Select Open.

В меню вид выберите Обозреватель решений. From the View menu, select Solution Explorer.

В окне Обозреватель решений выберите решение GettingStarted (верхний узел), а затем в контекстном меню выберите добавить > Новый проект . In the Solution Explorer window, select the GettingStarted solution (top node), and then select Add > New Project from the shortcut menu.

В левой части окна Добавление нового проекта выберите категорию Рабочий стол Windows в разделе Visual C# или Visual Basic. In the Add New Project window, on the left side, select the Windows Desktop category under Visual C# or Visual Basic.

Выберите шаблон консольное приложение (.NET Framework) и введите GettingStartedHost в поле имя. Select the Console App (.NET Framework) template, and enter GettingStartedHost for the Name. Щелкните ОК. Select OK.

Добавьте ссылку в проект GettingStartedHost в проект жеттингстартедлиб : Add a reference in the GettingStartedHost project to the GettingStartedLib project:

В окне Обозреватель решений выберите папку References в проекте GettingStartedHost , а затем в контекстном меню выберите пункт Добавить ссылку . In the Solution Explorer window, select the References folder under the GettingStartedHost project, and then select Add Reference from the shortcut menu.

В диалоговом окне Добавление ссылки в разделе проекты в левой части окна выберите решение. In the Add Reference dialog, under Projects on the left side of the window, select Solution.

Выберите жеттингстартедлиб в центральном разделе окна, а затем нажмите кнопку ОК. Select GettingStartedLib in the center section of the window, and then select OK.

Это действие делает типы, определенные в проекте жеттингстартедлиб , доступными для проекта GettingStartedHost . This action makes the types defined in the GettingStartedLib project available to the GettingStartedHost project.

Добавьте ссылку в проект GettingStartedHost в System.ServiceModel сборку: Add a reference in the GettingStartedHost project to the System.ServiceModel assembly:

В окне Обозреватель решений выберите папку References в проекте GettingStartedHost , а затем в контекстном меню выберите пункт Добавить ссылку . In the Solution Explorer window, select the References folder under the GettingStartedHost project, and then select Add Reference from the shortcut menu.

В окне Добавление ссылки в разделе сборки в левой части окна выберите платформа. In the Add Reference window, under Assemblies on the left side of the window, select Framework.

Выберите System. ServiceModelи нажмите кнопку ОК. Select System.ServiceModel, and then select OK.

Сохраните решение, выбрав файл > сохранить все. Save the solution by selecting File > Save All.

Добавление кода для размещения службы Add code to host the service

Чтобы разместить службу, добавьте код для выполнения следующих действий. To host the service, you add code to do the following steps:

  1. Создайте универсальный код ресурса (URI) для базового адреса. Create a URI for the base address.
  2. Создайте экземпляр класса для размещения службы. Create a class instance for hosting the service.
  3. Создайте конечную точку службы. Create a service endpoint.
  4. Включите обмен метаданными. Enable metadata exchange.
  5. Откройте узел службы, чтобы прослушивать входящие сообщения. Open the service host to listen for incoming messages.

Внесите следующие изменения в код: Make the following changes to the code:

Откройте файл Program.CS или Module1. vb в проекте GettingStartedHost и замените его код следующим кодом: Open the Program.cs or Module1.vb file in the GettingStartedHost project and replace its code with the following code:

Сведения о том, как работает этот код, см. в статье этапы программы размещения службы. For information about how this code works, see Service hosting program steps.

Обновите свойства проекта: Update the project properties:

В окне Обозреватель решений выберите папку GettingStartedHost , а затем в контекстном меню выберите пункт Свойства . In the Solution Explorer window, select the GettingStartedHost folder, and then select Properties from the shortcut menu.

На странице свойства GettingStartedHost выберите вкладку приложение : On the GettingStartedHost properties page, select the Application tab:

Для проектов C# выберите GettingStartedHost. Program из списка автоматически запускаемых объектов . For C# projects, select GettingStartedHost.Program from the Startup object list.

Для Visual Basic проектов выберите Service. Program из списка автоматически запускаемых объектов . For Visual Basic projects, select Service.Program from the Startup object list.

В меню файл выберите сохранить все. From the File menu, select Save All.

Проверка работоспособности службы Verify the service is working

Выполните сборку решения, а затем запустите консольное приложение GettingStartedHost в Visual Studio. Build the solution, and then run the GettingStartedHost console application from inside Visual Studio.

Служба должна запускаться с правами администратора. The service must be run with administrator privileges. Так как вы открыли Visual Studio с правами администратора, при запуске GettingStartedHost в Visual Studio приложение также запускается с правами администратора. Because you opened Visual Studio with administrator privileges, when you run GettingStartedHost in Visual Studio, the application is run with administrator privileges as well. В качестве альтернативы можно открыть новую командную строку от имени администратора (в контекстном меню выберите больше > запуска от имени администратора ) и выполнить в ней GettingStartedHost.exe . As an alternative, you can open a new command prompt as an administrator (select More > Run as administrator from the shortcut menu) and run GettingStartedHost.exe within it.

Откройте веб-браузер и перейдите на страницу службы по адресу http://localhost:8000/GettingStarted/CalculatorService . Open a web browser and browse to the service’s page at http://localhost:8000/GettingStarted/CalculatorService .

Для таких служб требуется разрешение на регистрацию HTTP-адресов на компьютере для прослушивания. Services such as this one require the proper permission to register HTTP addresses on the machine for listening. Учетные записи с уровнем доступа администратора имеют данное разрешение, а остальным учетным записям должно быть предоставлено разрешение на использование пространства имен HTTP. Administrator accounts have this permission, but non-administrator accounts must be granted permission for HTTP namespaces. Дополнительные сведения о настройке резервирования пространств имен см. в разделе Настройка протоколов HTTP и HTTPS. For more information about how to configure namespace reservations, see Configuring HTTP and HTTPS.

Читайте также:  Windows не удалось проверить диск закройте это диалоговое

Шаги программы размещения службы Service hosting program steps

Шаги в коде, добавленном для размещения службы, описаны ниже. The steps in the code you added to host the service are described as follows:

Шаг 1. Создайте экземпляр Uri класса для хранения базового адреса службы. Step 1: Create an instance of the Uri class to hold the base address of the service. URL-адрес, содержащий базовый адрес, имеет необязательный URI, идентифицирующий службу. A URL that contains a base address has an optional URI that identifies a service. Базовый адрес форматируется следующим образом: :// / . The base address is formatted as follows: :// / . Базовый адрес службы калькулятора использует транспорт HTTP, localhost, порт 8000 и сегмент URI GettingStarted. The base address for the calculator service uses the HTTP transport, localhost, port 8000, and the URI segment, GettingStarted.

Шаг 2. Создайте экземпляр ServiceHost класса, который используется для размещения службы. Step 2: Create an instance of the ServiceHost class, which you use to host the service. Конструктор принимает два параметра: тип класса, который реализует контракт службы, и базовый адрес службы. The constructor takes two parameters: the type of the class that implements the service contract and the base address of the service.

Шаг 3. Создание ServiceEndpoint экземпляра. Step 3: Create a ServiceEndpoint instance. Конечная точка службы состоит из адреса, привязки и контракта службы. A service endpoint is composed of an address, a binding, and a service contract. ServiceEndpointКонструктор состоит из типа интерфейса контракта службы, привязки и адреса. The ServiceEndpoint constructor is composed of the service contract interface type, a binding, and an address. Контракт службы — ICalculator . Он определен и реализуется в типе службы. The service contract is ICalculator , which you defined and implement in the service type. Привязка для этого образца — это WSHttpBinding встроенная привязка, которая подключается к конечным точкам, которые соответствуют спецификациям WS-*. The binding for this sample is WSHttpBinding, which is a built-in binding and connects to endpoints that conform to the WS-* specifications. Дополнительные сведения о привязках WCF см. в разделе Общие сведения о привязках WCF. For more information about WCF bindings, see WCF bindings overview. Добавьте адрес к базовому адресу, чтобы обозначить конечную точку. You append the address to the base address to identify the endpoint. Код определяет адрес как CalculatorService и полный адрес конечной точки как http://localhost:8000/GettingStarted/CalculatorService . The code specifies the address as CalculatorService and the fully qualified address for the endpoint as http://localhost:8000/GettingStarted/CalculatorService .

Для .NET Framework версии 4 и более поздних версий Добавление конечной точки службы является необязательным. For .NET Framework Version 4 and later, adding a service endpoint is optional. В этих версиях, если не добавить код или конфигурацию, WCF добавляет одну конечную точку по умолчанию для каждого сочетания базового адреса и контракта, реализуемого службой. For these versions, if you don’t add your code or configuration, WCF adds one default endpoint for each combination of base address and contract implemented by the service. Дополнительные сведения о конечных точках по умолчанию см. в разделе Указание адреса конечной точки. For more information about default endpoints, see Specifying an endpoint address. Дополнительные сведения о конечных точках, привязках и поведении по умолчанию см. в разделе упрощенная конфигурация и упрощенная конфигурация для служб WCF. For more information about default endpoints, bindings, and behaviors, see Simplified configuration and Simplified configuration for WCF services.

Шаг 4. Включение обмена метаданными. Step 4: Enable metadata exchange. Клиенты используют обмен метаданными для создания учетных записей-посредников для вызова операций службы. Clients use metadata exchange to generate proxies for calling the service operations. Чтобы включить обмен метаданными, создайте ServiceMetadataBehavior экземпляр, присвойте его HttpGetEnabled свойству значение true , а затем добавьте ServiceMetadataBehavior объект в Behaviors коллекцию ServiceHost экземпляра. To enable metadata exchange, create a ServiceMetadataBehavior instance, set its HttpGetEnabled property to true , and add the ServiceMetadataBehavior object to the Behaviors collection of the ServiceHost instance.

Шаг 5. Откройте ServiceHost для прослушивания входящих сообщений. Step 5: Open ServiceHost to listen for incoming messages. Приложение ожидает нажатия клавиши Ввод. The application waits for you to press Enter. После создания экземпляра приложения ServiceHost он выполняет блок try/catch. After the application instantiates ServiceHost, it executes a try/catch block. Дополнительные сведения о безопасном перехвате исключений, создаваемых ServiceHost , см. в разделе Использование закрытия и прерывания для освобождения ресурсов клиента WCF. For more information about safely catching exceptions thrown by ServiceHost, see Use Close and Abort to release WCF client resources.

При добавлении библиотеки службы WCF Visual Studio размещает ее для вас при его отладке, запуская узел службы. When you add a WCF service library, Visual Studio hosts it for you if you debug it by starting a service host. Чтобы избежать конфликтов, можно запретить Visual Studio размещать библиотеку службы WCF. To avoid conflicts, you can prevent Visual Studio from hosting the WCF service library.

  1. Выберите проект жеттингстартедлиб в Обозреватель решений и в контекстном меню выберите пункт Свойства . Select the GettingStartedLib project in Solution Explorer and choose Properties from the shortcut menu.
  2. Выберите параметры WCF и снимите флажок запустить узел службы WCF при отладке другого проекта в том же решении. Select WCF Options and uncheck Start WCF Service Host when debugging another project in the same solution.

Дальнейшие действия Next steps

В этом руководстве вы узнали, как выполнять следующие задачи: In this tutorial, you learned how to:

  • Создание и Настройка проекта консольного приложения для размещения службы WCF. Create and configure a console app project for hosting a WCF service.
  • Добавьте код для размещения службы WCF. Add code to host the WCF service.
  • Обновите файл конфигурации. Update the configuration file.
  • Запустите службу WCF и убедитесь, что она запущена. Start the WCF service and verify it’s running.

Перейдите к следующему руководству, чтобы научиться создавать клиент WCF. Advance to the next tutorial to learn how to create a WCF client.

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