- Общие сведения о службах рабочих процессов Workflow services overview
- Преимущества использования служб рабочих процессов Benefits of using workflow services
- Реализация службы рабочего процесса Implementing a workflow service
- Службы рабочих процессов и привязки на основе MSMQ Workflow services and MSMQ-based bindings
- Размещение службы рабочего процесса Hosting a workflow service
- Учебник. Создание клиента Windows Communication Foundation Tutorial: Create a Windows Communication Foundation client
- Создание клиента Windows Communication Foundation Create a Windows Communication Foundation client
- Средство служебной программы метаданных ServiceModel ServiceModel Metadata Utility tool
- Файл конфигурации клиента Client configuration file
- Дальнейшие действия Next steps
Общие сведения о службах рабочих процессов Workflow services overview
Службы рабочих процессов — это службы на основе WCF, которые реализуются с помощью рабочих процессов. Workflow services are WCF-based services that are implemented using workflows. Службы рабочих процессов — это рабочие процессы, которые используют действия обмена сообщениями для отправки и получения сообщений Windows Communication Foundation (WCF). Workflow services are workflows that use the messaging activities to send and receive Windows Communication Foundation (WCF) messages. В.NET Framework 4.5 появилось несколько действий обмена сообщениями, позволяющих отправлять и получать сообщения из рабочего процесса. .NET Framework 4.5 introduces a number of messaging activities that allow you send and receive messages from within a workflow. Дополнительные сведения о действиях обмена сообщениями и о том, как их можно использовать для реализации различных шаблонов обмена сообщениями, см. в разделе действия обменасообщениями. For more information about messaging activities and how they can be used to implement different message exchange patterns, see Messaging Activities.
Преимущества использования служб рабочих процессов Benefits of using workflow services
По мере возрастания распределения приложений отдельные службы становятся ответственными за вызов других служб для передачи им некоторой части работы. As applications become increasingly distributed, individual services become responsible for calling other services to offload some of the work. Реализация таких вызовов в виде асинхронных операций в коде представляет некоторую сложность. Implementing these calls as asynchronous operations introduces some complexity into the code. Обработка ошибок добавляет некоторую сложность в форме обработки исключений и обеспечения подробных сведений об отслеживании. Error handling adds additional complexity in the form of handling exceptions and providing detailed tracking information. Довольно часто некоторые службы являются длительными и занимают ценные системные ресурсы при ожидании ввода. Some services are often long running and can take up valuable system resources while waiting for input. Вследствие этих причин распределенные приложения часто являются очень сложными и их трудно разрабатывать и поддерживать. Because of these issues, distributed applications are often very complex and difficult to write and maintain. Рабочие процессы являются естественным способом координации асинхронной работы, особенно вызовов внешних служб. Workflows are a natural way to express the coordination of asynchronous work, especially calls to external services. Рабочие процессы также достаточно эффективны при представлении длительных бизнес-процессов. Workflows are also effective at representing long-running business processes. Эти качества делают рабочий процесс великолепным активом для построения служб в распределенной среде. It is these qualities that make the workflow a great asset to building services in a distributed environment.
Реализация службы рабочего процесса Implementing a workflow service
При реализации службы WCF вы определяете несколько контрактов, описывающих службу и данные, которые она отправляет и получает. When implementing a WCF service, you define a number of contracts that describe the service and the data that it sends and receives. Данные, представленные в виде контрактов данных и сообщений. The data is represented as data contracts and message contracts. Службы WCF и службы рабочих процессов используют контракты данных и определения контрактов сообщений как часть описаний служб. Both WCF and workflow services use data contract and message contract definitions as part of service descriptions. Служба сама предоставляет метаданные (в форме WSDL) для описания операций службы. The service itself exposes metadata (in the form of WSDL) to describe the operations of the service. В WCF контракты службы и операций определяют службу и операции, которые она поддерживает. In WCF, service contracts and operation contracts define the service and the operations it supports. Однако в службе рабочего процесса эти контракты являются частью самого бизнес-процесса. However in a workflow service, these contracts are part of the business process itself. Они поставляются в метаданные процессом, называемым выводом контракта. They are exposed in metadata by a process called contract inference. При размещении службы рабочего процесса с использованием WorkflowServiceHost просматривается определение рабочего процесса и формируется контракт на основе набора действий по отправке и получению сообщений, обнаруженных в рабочем процессе. When a workflow service is hosted using WorkflowServiceHost, the workflow definition is examined and a contract is generated based on the set of messaging activities found in the workflow. В частности, для создания контракта используются следующие действия и свойства: In particular, the following activities and properties are used to generate the contract:
Конечным результатом вывода контракта является описание службы, использующее те же структуры данных, что и службы WCF и контракты операций. The end result of contract inference is a description of the service using the same data structures as WCF services and operation contracts. Затем эти сведения используются для предоставления WSDL для службы рабочего процесса. This information is then used to expose WSDL for the workflow service.
.NET Framework 4.6.1 .NET Framework 4.6.1 не позволяет писать службы рабочего процесса с использованием существующего определения контракта без дополнительных средств разработки. does not allow you to write workflow services using an existing contract definition without some additional tooling support. Контракты служб рабочих процессов создаются посредством процесса вывода, который был рассмотрен ранее. Workflow service contracts are created by the contract inference process discussed previously. Контракты сообщений и данных, тем не менее, полностью поддерживаются. Message contracts and data contracts are fully supported, however.
Службы рабочих процессов и привязки на основе MSMQ Workflow services and MSMQ-based bindings
WCF определяет две привязки на основе очереди сообщений (MSMQ) — NetMsmqBinding и MsmqIntegrationBinding. WCF defines two MSMQ-based bindings NetMsmqBinding and MsmqIntegrationBinding. Привязки на основе очереди сообщений (MSMQ) часто используются со службами рабочих процессов, что связано с продолжительностью работы таких служб. MSMQ-based bindings are often used with workflow services because of the long-running nature of such services. Привязки на основе очереди сообщений (MSMQ) имеют свойство ValidityDuration , определяющее срок, в течение которого сообщения MSMQ считаются достоверными. The MSMQ-based bindings have a ValidityDuration property that specifies how long MSMQ messages can assume to be valid. Из-за длительного срока работы служб рабочих процессов возможно, что длительность достоверности сообщения MSMQ закончится до того, как служба рабочих процессов сможет его обработать. Because of the long running nature of workflow services it is possible that the validity duration of a MSMQ message may elapse before the workflow service can process it. Поэтому очень важно задать для длительности достоверности привязки MSMQ подходящее значение. It is therefore very important to set the validity duration of a MSMQ binding to an appropriate value. Это значение должно выбираться на основе рабочего процесса и способа, с помощью которого он обрабатывает сообщения. This value must be chosen based on the workflow and how it processes messages. Например, если имеется рабочий процесс с действием Receive, сопровождаемым пользовательским действием, которое выполняется 10 минут, и действием Receive, правильное значение ValidityDuration должно превышать 10 минут. For example if you have a workflow with a Receive activity followed by a custom activity that takes 10 minutes to run, followed by another Receive activity, the correct value for ValidityDuration would be greater than 10 minutes.
Размещение службы рабочего процесса Hosting a workflow service
Как и службы WCF, необходимо размещать службы рабочих процессов. Like WCF services, workflow services must be hosted. Службы WCF используют ServiceHost класс для размещения служб и служб рабочих процессов, используемых WorkflowServiceHost для размещения служб. WCF services use the ServiceHost class to host services and workflow services use WorkflowServiceHost to host services. Как и службы WCF, службы рабочих процессов могут размещаться различными способами, например: Like WCF services, workflow services can be hosted in a variety of ways, for example:
В управляемом платформа .NET Framework приложении. In a managed .NET Framework application.
В службах IIS. In Internet Information Services (IIS).
в службе WAS; In Windows Process Activation Service (WAS).
в управляемой службе Windows. In a managed Windows Service.
Службы рабочего процесса, размещенные в управляемом платформа .NET Framework приложении или управляемой службе Windows, создают экземпляр WorkflowServiceHost класса и передают ему экземпляр WorkflowService , содержащий определение рабочего процесса в пределах Body Свойства. Workflow services hosted in a managed .NET Framework application or a managed Windows service create an instance of the WorkflowServiceHost class and pass it an instance of the WorkflowService that contains the workflow definition within the Body property. Определение рабочего процесса, содержащее действия обмена сообщениями, предоставлено службой рабочего процесса. A workflow definition that contains messaging activities is exposed as a workflow service.
Учебник. Создание клиента Windows Communication Foundation Tutorial: Create a Windows Communication Foundation client
В этом руководстве описываются четвертые из пяти задач, необходимых для создания базового приложения Windows Communication Foundation (WCF). This tutorial describes the fourth 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 create a client by retrieving metadata from a WCF service. Для добавления ссылки на службу, которая получает метаданные из конечной точки обмена метаданными службы, используется Visual Studio. You use Visual Studio to add a service reference, which gets the metadata from the service’s MEX endpoint. Затем Visual Studio создает управляемый файл исходного кода для прокси клиента на выбранном языке. Visual Studio then generates a managed source code file for a client proxy in the language you’ve chosen. Он также создает файл конфигурации клиента (App.config). It also creates a client configuration file (App.config). Этот файл позволяет клиентскому приложению подключаться к службе в конечной точке. This file enables the client application to connect to the service at an endpoint.
При вызове службы WCF из проекта библиотеки классов в Visual Studio используйте функцию Добавление ссылки на службу для автоматического создания прокси-сервера и связанного файла конфигурации. If you call a WCF service from a class library project in Visual Studio, use the Add Service Reference feature to automatically generate a proxy and associated configuration file. Однако, поскольку проекты библиотеки классов не используют этот файл конфигурации, необходимо добавить параметры в созданный файл конфигурации в файл App.config для исполняемого файла, вызывающего библиотеку классов. However, because class library projects don’t use this configuration file, you need to add the settings in the generated configuration file to the App.config file for the executable that calls the class library.
В качестве альтернативы для создания прокси-класса и файла конфигурации вместо Visual Studio следует использовать средство служебной программы для метаданных ServiceModel . As an alternative, use the ServiceModel Metadata Utility tool instead of Visual Studio to generate the proxy class and configuration file.
Клиентское приложение использует созданный прокси-класс для взаимодействия со службой. The client application uses the generated proxy class to communicate with the service. Эта процедура описана в разделе учебник. Использование клиента. This procedure is described in Tutorial: Use a client.
В этом руководстве вы узнаете, как: In this tutorial, you learn how to:
- Создание и Настройка проекта консольного приложения для клиента WCF. Create and configure a console app project for the WCF client.
- Добавьте ссылку на службу WCF для создания прокси-класса и файлов конфигурации. Add a service reference to the WCF service to generate the proxy class and configuration files.
Создание клиента Windows Communication Foundation Create a Windows Communication Foundation client
Создание проекта консольного приложения в 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) и введите GettingStartedClient в поле имя. Select the Console App (.NET Framework) template, and enter GettingStartedClient for the Name. Щелкните ОК. Select OK.
Добавьте ссылку в проект GettingStartedClient в System.ServiceModel сборку: Add a reference in the GettingStartedClient project to the System.ServiceModel assembly:
В окне Обозреватель решений выберите папку References в проекте GettingStartedClient , а затем в контекстном меню выберите пункт Добавить ссылку . In the Solution Explorer window, select the References folder under the GettingStartedClient 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, а затем нажмите кнопку ОК. Find and select System.ServiceModel, and then choose OK.
Сохраните решение, выбрав файл > сохранить все. Save the solution by selecting File > Save All.
Добавьте ссылку на службу в службу калькулятора: Add a service reference to the calculator service:
В окне Обозреватель решений выберите папку References в проекте GettingStartedClient , а затем в контекстном меню выберите Добавление ссылки на службу . In the Solution Explorer window, select the References folder under the GettingStartedClient project, and then select Add Service Reference from the shortcut menu.
В окне Добавление ссылки на службу выберите Обнаружение. In the Add Service Reference window, select Discover.
Служба CalculatorService запускается, и Visual Studio отображает ее в окне службы . The CalculatorService service starts and Visual Studio displays it in the Services box.
Выберите CalculatorService , чтобы развернуть его и отобразить контракты службы, реализованные службой. Select CalculatorService to expand it and display the service contracts implemented by the service. Оставьте пространство имен по умолчанию и нажмите кнопку ОК. Leave the default Namespace and choose OK.
Visual Studio добавит новый элемент в папку подключенные службы проекта GettingStartedClient . Visual Studio adds a new item under the Connected Services folder in the GettingStartedClient project.
Средство служебной программы метаданных ServiceModel ServiceModel Metadata Utility tool
В следующих примерах показано, как при необходимости использовать средство служебной программы метаданных ServiceModel (Svcutil.exe) для создания файла прокси-класса. The following examples show how to optionally use the ServiceModel Metadata Utility tool (Svcutil.exe) to generate the proxy class file. Это средство создает файл прокси-класса и файл App.config . This tool generates the proxy class file and the App.config file. В следующих примерах показано, как создать прокси-сервер в C# и Visual Basic соответственно: The following examples show how to generate the proxy in C# and Visual Basic, respectively:
Файл конфигурации клиента Client configuration file
После создания клиента Visual Studio создаст файл конфигурации App.config в проекте GettingStartedClient , который должен быть похож на следующий пример: After you’ve created the client, Visual Studio creates the App.config configuration file in the GettingStartedClient project, which should be similar to the following example:
В разделе Обратите внимание на элемент. Under the section, notice the element. Элемент ** ** определяет конечную точку, которую клиент использует для доступа к службе следующим образом: The element defines the endpoint that the client uses to access the service as follows:
- Адрес: http://localhost:8000/GettingStarted/CalculatorService . Address: http://localhost:8000/GettingStarted/CalculatorService . Адрес конечной точки. The address of the endpoint.
- Контракт службы: ServiceReference1.ICalculator . Service contract: ServiceReference1.ICalculator . Контракт службы обрабатывает взаимодействие между клиентом WCF и службой. The service contract handles communication between the WCF client and the service. Visual Studio создала этот контракт при использовании функции Добавление ссылки на службу . Visual Studio generated this contract when you used its Add Service Reference function. По сути, это копия контракта, определенного в проекте Жеттингстартедлиб. It’s essentially a copy of the contract that you defined in the GettingStartedLib project.
- Привязка: WSHttpBinding . Binding: WSHttpBinding. Привязка указывает HTTP как транспорт, взаимодействующую безопасность и другие сведения о конфигурации. The binding specifies HTTP as the transport, interoperable security, and other configuration details.
Дальнейшие действия Next steps
В этом руководстве вы узнали, как выполнять следующие задачи: In this tutorial, you learned how to:
- Создание и Настройка проекта консольного приложения для клиента WCF. Create and configure a console app project for the WCF client.
- Добавьте ссылку на службу WCF, чтобы создать класс прокси и файлы конфигурации для клиентского приложения. Add a service reference to the WCF service to generate the proxy class and configuration files for the client application.
Перейдите к следующему руководству, чтобы узнать, как использовать созданный клиент. Advance to the next tutorial to learn how to use the generated client.