Step-by-Step release of the WCF Service to the Windows Service

Source: Internet
Author: User

Just now we have released WCF to IIS. Next we will release WCF to the Windows service.

WCF is a good thing. There are indeed many praises for it, and it is the crystallization of the wisdom of countless Microsoft developers. If you are learning or using WCF, I am really happy for you, when I went to school, it took so much professional knowledge and time to solve compatibility and balance performance issues. However, for the current WCF, you only need simple configuration.

The first step is to use the new technology without falling behind the times.

How to: host a WCF Service in a hosted Windows Service

This topic provides an overview of the basic steps required to create a Windows Communication Foundation (WCF) Service hosted by a Windows service. This scheme can be enabled through the hosted Windows Service bearer option, which is a long-running WCF Service that is hosted outside Internet Information Service (IIS) in a secure environment without message activation. The operating system controls the service lifetime. This host option is available in all versions of Windows.

You can use Microsoft. managementconsole. snapin in the Microsoft Management Console (MMC) to manage Windows Services and configure it to automatically start when the system starts. This bearer option includes registering an application domain that hosts the WCF Service as a Windows service. Therefore, the Process lifetime of the service is controlled by the Windows Service's Service Control Manager (SCM.

The Service Code includes the service implementation of the service agreement, the Windows service class, And the installer class. The service implementation class calculatorservice is a WCF Service. Calculatorwindowsservice is a Windows service. To meet the requirements of Windows Services, this class inherits from servicebase and implements the onstart and onstop methods. In onstart, servicehost is created for the calculatorservice type and opened. In onstop, stop and release the service. The host is also responsible for providing the service host base address, which has been set in application settings. The installer class inherits from
Installer, which allows programs to install Windows Services through the installutil.exe tool.
Construct services and provide host code

Use the calculator service interface in the service. CS file to define the icalculator service agreement.

By inheriting from the WCF icalculator interface, the service agreement is implemented as a WCF Service in the calculatorservice class of the service. CS file.

Windows Services are implemented by inheriting from the servicebase class. Override the onstart method to create and open the servicehost instance. Override the onstop method to disable the servicehost instance. Create a calculatorservice instance and name it "wcfwindowsservicesample ". Provides the entry point for the application.

Create a projectinstaller class. This class inherits from the installer and is marked with runinstallerattribute set to true. Therefore, you can call the Visual Studio custom operation installer or installutil.exe when installing the assembly.

The base address of the service provided in the configuration.
Install and run the service

Compile the service to generate the service.exe executable file.

Type installutil bin \ service.exe at the command prompt to install the Windows service. (If the path of the tool has not been set, the tool is placed in the Microsoft. NET Framework installation directory .) Type Services. MSC at the command prompt to access the service Control Manager (SCM ). Windows Service should appear in the service as "wcfwindowsservicesample. The WCF Service can respond to the client only when the Windows service is running. To start the service, right-click the service in SCM and select "start", or type
Net start wcfwindowsservicesample.

If you change the service, you must stop and uninstall the service first. To stop the service, right-click the service in SCM and select "stop", or type net stop wcfwindowsservicesample at the command prompt. Note that if you stop the Windows Service and run the client, an endpointnotfoundexception exception occurs when the client attempts to access the service. To uninstall the Windows Service, type installutil/u bin \ service.exe at the command prompt.
Example

The following code demonstrates how to use the content of the service. CS file for the implementation of protocols and protocols, as well as Windows service installation and host code.

Like the "self-bearer" option, the Windows service host environment requires that some host code be written as part of the application. The service is implemented as a. exe program and contains its own host code. In other host environments (such as Windows Process activation Service (was) hosts in Internet Information Service (IIS), developers do not have to write host code.

 

1: Preface

We all know that WCF must provide its own host to carry the service during running. Instead of hosting, WCF provides a servicehost class that allows you to host the WCF Service in your own applications. Then, call the open method of servicehost. We know that WCF is a set of technologies for SOA. for SOA, we must ensure that the services can run normally and smoothly. Therefore, it is very important to host our services and what to host our services, therefore, it is necessary to select an appropriate host Method for our applications.

2: Common host types

You can use Visual Studio. NET to create the following types of managed applications:

Winforms Application

Console Application

Windows Services

Web applications hosted in Internet Information Service (IIS)

Below I will take a demo as an example to introduce these commonly used hosts.

3: Hoster features

When selecting an application type, you must consider certain requirements. servicehost must be instantiated to provide the bearer environment required to run the service. Console applications and winforms applications usually run on users' desktops. They are visible on the desktop and can carry your services with poor security. Therefore, they are not suitable for enterprise hosts. Because we want to enable our enterprise services to support more and more services, it is obviously not suitable when using console applications and winforms applications as the host, in this architecture ,. These are suitable for enterprise hosts that generally meet high availability requirements, for example. Therefore, we cannot use the console or winforms application as a host for the enterprise. The only feasible solution is
The service is hosted on IIS or its host is sent to the Windows service. In fact, we usually use Windows applicatin or console application as the host during project development. this is conducive to debugging and testing. During project deployment, we usually choose IIS or Windows service as the host. IIS has many advantages, and it provides many functions,

4: soultion Structure

 

This soultion mainly introduces three hosts, namely console applicatin, Windows service, and IIS, because Windows application and console application are not much different.

First, we will introduce host WCF Service in Windows Services. windows service is a process managed by the operating system. NET environment has provided such a template, with Windows Services as a host is a good choice:

Windows Services HOST: wcfwindowsserviceshost in application solution.

Services contract and services

[Servicecontract]
Public interface itest
{
[Operationcontract]
Double add (Double X, Double Y );
}

Public class test: itest
{

Public double add (Double X, Double Y)
{
Return X + Y;
}

}

5: Windows Services host

First, create a Windows service project.

 

The Windows Services project contains two files: service1.cs and program. CS. The service1.cs file contains the service implementation, while the program. CS file is used for instantiation and essentially carries the Windows service. To host the WCF Service within the Windows service, you only need to execute the START () method and stop () method of the Windows service.

Servicehost host;
Public windowservicetest ()
{
Initializecomponent ();
}

Protected override void onstart (string [] ARGs)
{
Host = new servicehost (typeof (TEST ));
Host. open ();
}

Protected override void onstop ()
{
Host. Close ();
}
Configuration file:

<System. servicemodel>
<Behaviors>
<Endpointbehaviors>
<Behavior name = "leleapplicationhost">
</Behavior>
</Endpointbehaviors>
</Behaviors>
<Bindings>
<Basichttpbinding>
<Binding name = "basicbinding"> </binding>
</Basichttpbinding>
</Bindings>
<Services>
<Service name = "wcfhostservices. Test">
<Endpoint address = "" binding = "basichttpbinding" bindingconfiguration = "basicbinding" Contract = "wcfhostcontract. itest" behaviorconfiguration = "leleapplicationhost">
</Endpoint>
<Host>
<Baseaddresses>
<Add baseaddress = "http: // localhost/windowsservicetest"/>
</Baseaddresses>
</Host>
</Service>
</Services>
</System. servicemodel>

In fact, we can see that writing a host on Windows Services for the WCF Service is very simple. Windows Services has many advantages, such as starting with the operating system without manual enabling, in addition, it is not limited to your binding technology. It is also difficult to say that Windows Service has so many advantages. For example, to install Windows service.we have installed services through the installutil.exe tool or through custom operations in the installation package. This tool will come with it after installing the SDK, and installutil is easy to use. The following uses the custom installation service as an example.

 

Open the designer view of the service class in the Windows service project. Right-click the window and click "add installer". A component named projectinstaller is added. Double-click this file in the project and there is a servicesinstall1 component, right-click to modify his name and Startup type,

 

 

To create an installer for installing Windows Services, we need to add the installer and deployment project (windowsservicesetup) to solution ). The following steps describe how to add setup and deployment projects to a solution:

Create an installation project:

 

1: Right-click the installation project, point to "add", select "project output", and select Windows Service appliation... select main output,

2: Right-click the installation project and choose View> custome action.

 

3: Right-click customer action and add the primary output file to custome action.

4: generate a project and install it. In this way, we can start our servcies. We can open the windows services management tool to view the installed servcie.

 

 

6: IIS HOST

To host WCF services in IIS, a file with the extension. SVC is required. In fact, such a template has been provided in our project template. This file associates the service with its implementation and is a means for IIS to automatically create servicehost. IIS will take over the interaction between the service and servicehost, and you do not have to instantiate and start servicehost by yourself .. The first line of the SVC file contains a command in the ASP. NET <% PAGE %> command to indicate the service to which the file points. In IIS, the default behavior for carrying the WCF Service is that this IIS controls servicehost
.

We can create a WCF services application, which will automatically generate a file for service. SVC.

 

You can also add an SVC file to another project template:

 

<% @ Servicehost Language = "C #" DEBUG = "true" service = "wcfiishost. Test" codebehind = "test. SVC. cs" %>

Running host in IIS means that you must set the WCF configuration in the web. config file of the application. Web. config is as follows:

<System. servicemodel>
<Services>
<Service behaviorconfiguration = "wcfiishost. service1behavior"
Name = "wcfiishost. Test">
<Endpoint address = "" binding = "wshttpbinding" Contract = "wcfiishost. itest">
<Identity>
<DNS value = "localhost"/>
</Identity>
</Endpoint>
<Endpoint address = "mex" binding = "mexhttpbinding" Contract = "imetadataexchange"/>
</Service>
</Services>
<Behaviors>
<Servicebehaviors>
<Behavior name = "wcfiishost. service1behavior">
<! -- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<Servicemetadata httpgetenabled = "true"/>
<! -- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<Servicedebug includeexceptiondetailinfaults = "false"/>
</Behavior>
</Servicebehaviors>
</Behaviors>
</System. servicemodel>

In IIS, the default behavior of host WCF services is that this IIS controls the instantiation of servicehost. On the client side, we directly reference the address. By default, the proxy file is generated on our client. We do not need to use the svcutil tool to generate the agent on the client side.

Note: The endpoint address should be empty, so that the SVC file will determine the base address of the service.

7: console application host

This method is simple, because most of the time we test the project, we use this host,

Config:

<System. servicemodel>
<Behaviors>
<Endpointbehaviors>
<Behavior name = "leleapplicationhost">
</Behavior>
</Endpointbehaviors>
</Behaviors>
<Bindings>
<Basichttpbinding>
<Binding name = "basicbinding"> </binding>
</Basichttpbinding>
</Bindings>
<Services>
<Service name = "wcfhostservices. Test">
<Endpoint address = "" binding = "basichttpbinding" bindingconfiguration = "basicbinding" Contract = "wcfhostcontract. itest" behaviorconfiguration = "leleapplicationhost">
</Endpoint>
<Host>
<Baseaddresses>
<Add baseaddress = "http: // localhost/consoletest"/>
</Baseaddresses>
</Host>
</Service>
</Services>
</System. servicemodel>

Start Host:

Using (servicehost host = new servicehost (typeof (TEST )))
{
Host. open ();
Console. writeline ("services has begun listenting ");
Console. readkey ();
}

Client:

Public class coclient: clientbase <wcfhostcontract. itest>, itest
{
Public double add (Double X, Double Y)
{
Return this. Channel. Add (x, y );
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.