Wcf windows services что это

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

В меню файл выберите команду Открыть > проект или решение и перейдите к созданному ранее решению 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:

Читайте также:  Linux grep exclude string

В окне Обозреватель решений выберите папку 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.

Читайте также:  Служба беспроводной связи windows не запущена как исправить

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

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

Читайте также:  Ssd диск долго загружается windows

Для .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.

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