Практическое руководство. Размещение службы 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.
В этом примере конечные точки явно задаются в файле конфигурации. 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.
Пошаговое руководство. Создание простой службы WCF в Windows Forms Walkthrough: Create a simple WCF service in Windows Forms
В этом пошаговом руководстве показано, как создать простую службу Windows Communication Foundation (WCF), проверить ее, а затем получить к ней доступ из Windows Forms приложения. This walkthrough demonstrates how to create a simple Windows Communication Foundation (WCF) service, test it, and then access it from a Windows Forms application.
Отображаемые на компьютере имена или расположения некоторых элементов пользовательского интерфейса Visual Studio могут отличаться от указанных в этой статье. Your computer might show different names or locations for some of the Visual Studio user interface elements in this article. Возможно, вы используете другой выпуск Visual Studio или другие параметры среды. You may be using a different edition of Visual Studio or different environment settings. Дополнительные сведения см. в разделе Персонализация среды IDE. For more information, see Personalize the IDE.
Создание службы Create a service
В меню Файл щелкните Создать > Проект. On the File menu, choose New > Project.
В диалоговом окне Новый проект разверните узел Visual Basic или Visual C# и выберите WCF, а затем — библиотеку служб WCF. In the New Project dialog box, expand the Visual Basic or Visual C# node and choose WCF, followed by WCF Service Library.
Чтобы создать проект, нажмите кнопку ОК . Click OK to create the project.
На начальном экране выберите Создать проект. On the start window, choose Create a new project.
Введите библиотеку служб WCF в поле поиска на странице Создание нового проекта . Type wcf service library in the search box on the Create a new project page. Выберите шаблон C# или Visual Basic для библиотеки службы WCF, а затем нажмите кнопку Далее. Select either the C# or Visual Basic template for WCF Service Library, and then click Next.
Если шаблоны не отображаются, может потребоваться установить компонент Windows Communication Foundation Visual Studio. If you don’t see any templates, you may need to install the Windows Communication Foundation component of Visual Studio. Выберите установить дополнительные инструменты и компоненты , чтобы открыть Visual Studio Installer. Choose Install more tools and features to open Visual Studio Installer. Перейдите на вкладку отдельные компоненты , прокрутите вниз до пункта действия разработки, а затем выберите Windows Communication Foundation. Choose the Individual components tab, scroll down to Development activities, and then select Windows Communication Foundation. Нажмите кнопку Изменить. Click Modify.
На странице Настройка нового проекта нажмите кнопку создать. On the Configure your new project page, click Create.
Будет создана работающая служба, которую можно протестировать и использовать. This creates a working service that can be tested and accessed. Следующие два действия демонстрируют, как можно изменить метод по умолчанию для использования другого типа данных. The following two steps demonstrate how you might modify the default method to use a different data type. В реальном приложении необходимо также добавить к службе ее специальные функции. In a real application, you would also add your own functions to the service.
В Обозреватель решенийдважды щелкните IService1. vb или IService1.CS. In Solution Explorer, double-click IService1.vb or IService1.cs.
Найдите следующую строку: Find the following line:
Измените тип value параметра на String: Change the type for the value parameter to string:
В приведенном выше коде обратите внимание на атрибуты или [OperationContract] . In the above code, note the or [OperationContract] attributes. Эти атрибуты обязательны для любого метода, предоставляемого службой. These attributes are required for any method exposed by the service.
В Обозреватель решенийдважды щелкните Service1. vb или Service1.CS. In Solution Explorer, double-click Service1.vb or Service1.cs.
Найдите следующую строку: Find the following line:
Измените тип value параметра на String: Change the type for the value parameter to string:
Тестирование службы Test the service
Нажмите клавишу F5, чтобы запустить службу. Press F5 to run the service. Откроется форма тестового клиента WCF , которая загружает службу. A WCF Test Client form appears and loads the service.
В форме Тестовый клиент WCF дважды щелкните метод GetData() в разделе IService1. In the WCF Test Client form, double-click the GetData() method under IService1. Откроется вкладка GetData . The GetData tab appears.
В диалоговом окне Запрос выберите поле Значение и введите Hello . In the Request box, select the Value field and type Hello .
Нажмите кнопку Вызвать. Click the Invoke button. Если появится диалоговое окно » предупреждение системы безопасности «, нажмите кнопку ОК. If a Security Warning dialog box appears, click OK. Результат отобразится в поле ответ . The result displays in the Response box.
В меню Файл щелкните Выход, чтобы закрыть тестовую форму. On the File menu, click Exit to close the test form.
Доступ к службе Access the Service
Ссылка на службу WCF Reference the WCF service
В меню файл выберите команду Добавить , а затем — Новый проект. On the File menu, point to Add and then click New Project.
В диалоговом окне Новый проект разверните узел Visual Basic или Visual C# , выберите пункт Windows, а затем выберите Windows Forms приложение. In the New Project dialog box, expand the Visual Basic or Visual C# node, select Windows, and then select Windows Forms Application. Нажмите кнопку ОК, чтобы открыть проект. Click OK to open the project.
Щелкните правой кнопкой мыши WindowsApplication1 и выберите команду Добавить ссылку на службу. Right-click WindowsApplication1 and click Add Service Reference. Откроется диалоговое окно Добавить ссылку на службу. The Add Service Reference dialog box appears.
В диалоговом окне Добавление ссылки на службу выберите Найти. In the Add Service Reference dialog box, click Discover.
Service1 отображается в области службы . Service1 displays in the Services pane.
Нажмите кнопку ОК, чтобы добавить ссылку на службу. Click OK to add the service reference.
Создайте клиентское приложение Build a client application
В Обозревателе решений дважды щелкните Form1.vb или Form1.cs, чтобы открыть конструктор Windows Forms, если он еще не открыт. In Solution Explorer, double-click Form1.vb or Form1.cs to open the Windows Forms Designer if it is not already open.
Из Панели элементов перетащите на форму элемент управления TextBox , элемент управления Label и элемент управления Button . From the Toolbox, drag a TextBox control, a Label control, and a Button control onto the form.
Дважды щелкните Button и добавьте следующий код в обработчик событий Click : Double-click the Button , and add the following code in the Click event handler:
В Обозревателе решений щелкните правой кнопкой мыши WindowsApplication1 и выберите команду Назначить запускаемым проектом. In Solution Explorer, right-click WindowsApplication1 and click Set as StartUp Project.
Нажмите клавишу F5 , чтобы запустить проект. Press F5 to run the project. Введите любой текст и нажмите кнопку. Enter some text and click the button. На этой метке отображается введенный текст:. The label displays «You entered:» and shows the text that you entered.