WCF host and service hosting

Source: Internet
Author: User
WCF host and service hosting

To publish the WCF Service, you must provide a host environment for running the service. Just like. Net CLR, you need to create a host environment to hostCodeGenerally, the host environment of WCF also runs in the process application.ProgramDomain. One or more servicehost instances can be created in the application domain, as shown in relationship 1:


Figure 1: hosting servicehost

It is not recommended that you create multiple servicehost instances in the application domain. To host multiple services, you can publish multiple WCF services through multiple endpoints in a single host. Because application domains are isolated from each other, it is necessary to create multiple servicehost instances to provide different security contexts.

Typical hosts of WCF include the following four types:

1. "Self-hosting" in a managed application (self-managed host)
2. Managed Windows Services (Windows Services host)
3. Internet Information Services (iis host)
4. Windows Process activation Service (was host)

The following describes how these hosts are hosted and related precautions through a specific instance. In such an instance, we define the following service contract:


Namespace brucezhang. WCF. documentsexplorerservicecontract
Public interface idocumentsexplorerservice
[Faultcontract (typeof (directorynotfoundexception)]
Documentlist fetchdocuments (string homedir );

Stream transferdocument (document );

The service implementation is as follows:


Namespace brucezhang. WCF. documentsexplorerserviceimplementation
[Servicebehavior (instancecontextmode = instancecontextmode. Single)]
Public class documentsexplorerservice: idocumentsexplorerservice
# Region idocumentsexplorerservice members

Public documentlist fetchdocuments (string homedir)
// Implementation code

Public stream transferdocument (document)
// Implementation code

# Endregion

In the service contract operation, documentlist and document are data contracts defined by themselves:


Namespace brucezhang. WCF. documentsexplorerdatacontract
Public class document
// Datamembers
Namespace brucezhang. WCF. documentsexplorerdatacontract
[Knowntype (typeof (document)]
Public class documentlist: ilist
// Ilist Methods

Note the namespace of the service contract, service and data contract defined above.

1. Self-managed host

Use servicehost provided by WCF The open () and close () methods are provided to facilitate developers to host services in console applications, Windows applications, and ASP. NET applications. Regardless of the application in the Self-hosted environment, the methods for hosting services are essentially the same. For example, in the console application:


Using (servicehost host = new servicehost (typeof (documentsexplorerservice )))
Host. open ();

Console. writeline ("the service had been launched .");
Console. Read ();

Because the servicehost instance is created in the application domain, we must ensure that the host process will not be shut down during service calling, so we use the console. read () to block the process so that the console application can run until it is deemed to be disabled. If it is a Windows application, you can place the code for creating the servicehost instance in the relevant code of the main form to ensure that the service host will not be closed.

Correspondingly, We need to configure the app. config configuration file of the application:


<System. servicemodel>
<Service name =

"Brucezhang. WCF. documentsexplorerserviceimplementation. documentsexplorerservice"

Behaviorconfiguration = "incluentexplorerservicebehavior">
<Add baseaddress = "http: // localhost: 8008/documentexplorerservice"/>
Address = ""
Binding = "basichttpbinding"
Bindingconfiguration = "documentexplorerservicebinding"
Contract = "brucezhang. WCF. documentsexplorerservicecontract. idocumentsexplorerservice"/>

<Endpoint address = "mex" binding = "mexhttpbinding" Contract = "imetadataexchange"/>
<Binding name = "documentexplorerservicebinding" sendtimeout = "00:10:00"

Transfermode = "streamed"
Messageencoding = "text" textencoding = "UTF-8"

Maxcompute edmessagesize = "9223372036854775807">
<Behavior name = "incluentexplorerservicebehavior">
<Servicemetadata httpgetenabled = "true"/>
</System. servicemodel>

Note: The service name in the configuration file must contain the service contract and service class namespace. In the configuration file The tag adds a base address for the service. Therefore, in the endpoint, the address is "".

In this case, the client configuration file that calls the service should also be consistent with the service configuration:



address = "http: // localhost: 8008/documentexplorerservice "
binding =" basichttpbinding "
bindingconfiguration =" documentexplorerservicebinding "
contract =" idocumentsexplorerservice "/>

transfermode = "streamed"
messageencoding = "text" textencoding = "UTF-8"

maxcompute edmessagesize = "9223372036854775807">

Note that the Service addresses in the two configuration files are the same, and the bound configurations are basically the same.

In common enterprise applications, we seldom use the self-Host Mode to host services. This is because the client can call services only when the application is running, it is not easy to start and stop services at any time. In addition to being easy-to-use and easy-to-manage, it imposes many restrictions on reliability, performance, and many other aspects. However, because it is simple and easy to implement, it is often used in debugging or demo environments during development.

The self-managed host supports all bindings.

2. Windows Services host

The Windows Services host completely overcomes the disadvantages of the Self-hosted host. It allows administrators to conveniently start or stop services and restart services after service failures. We can also use Service Control Manager to set the service as an automatic start mode, saving service management. In addition, Windows Services provides security, detection, and log mechanisms.

The implementation of Windows Services host is also very simple. You can create a Windows Services Project in Visual Studio. After creating a project, you can create a Windows service class that inherits the system. serviceprocess. servicebase class. The Windows service class inherits the onstart () and onstop () Methods of the servicebase class to start and stop the Windows service. We can override these two methods to put the startup and shutdown of servicehost into the implementation of these two methods. For example, the documentsexplorerwindowsservice class we created:



namespace brucezhang. WCF. documentsexplorer
{< br> Public partial class documentsexplorerwindowsservice: servicebase
{< br> private servicehost m_servicehost = NULL;

Public static void main ()
{< br> servicebase. run (New documentsexplorerwindowsservice ();

Public documentsexplorerwindowsservice ()
{< br> initializecomponent ();

servi CENAME = "documentsexplorerservice";

protected override void onstart (string [] ARGs)
{< br> If (m_servicehost! = NULL)
{< br> m_servicehost.close ();

m_servicehost = new servicehost (typeof (documentsexplorerservice ));
m_servicehost.open ();

protected override void onstop ()
{< br> If (m_servicehost! = NULL)
{< br> m_servicehost.close ();
m_servicehost = NULL;
}< BR >}

In the main function, we create a Windows service instance using the servicebase. Run () static method, and call the servicename attribute of the servicebase class to specify the service name in the constructor of the Windows service class. In the override onstart () method, we first determine whether a servicehost instance already exists. If it does not exist, we create it. The method for creating a servicehost instance is the same as that for creating a self-hosted host.

To create a servicehost instance, we also need to add the app. config configuration file in the project. The configuration file is exactly the same as before.

If you want to use the WCF Technology in enterprise applications, the best host method is Windows Services, especially when the operating system of the server is not Vista. It is easy to manage services and can maintain the service for a long period of time. It also supports all bindings, so it is limited to the minimum. However, the only defect in this method is the comparison between the local deployment and the local deployment. you can install the service host through the installutil.exe tool of .net.net (or you can perform the custom operation of the installation package ).

To install the service host, we also need to create its installation program. We can customize an installation class so that it inherits from the system. configuration. Install. installer class. The simpler method is to directly create an installation class through the design support provided by the Windows service. In the designer view of a Windows service such as documentsexplorerwindowsservice, right-click the service and select "add installer" from the shortcut menu:

Figure 2: add an installer

The created installer assumerserviceinstaller is as follows:



namespace brucezhang. WCF. documentsexplorer
{< br> // It needs be ran at the command mode
// type installutil filename to install the Windows Service
// type services. MSC to access the service Control Manager (SCM) and browse the Windows

// type installutil/U filename to uninstall the Windows Service
[runinstaller (true)]
Public partial class assumerserviceinstaller: installer
{< br> private serviceprocessinstaller m_process;
private serviceinstaller m_service;

Public assumerserviceinstaller ()
{< br> initializecomponent ();

m_process = new serviceprocessinstaller ();
m_process.account = serviceaccount. localSystem;
m_service = new serviceinstaller ();
m_service.servicename = "documentsexplorerservice";
installers. add (m_process);
installers. add (m_service);
}< BR >}

In the assumerserviceinstaller class, serviceaccount is an enumeration type and can be set to LocalService, LocalSystem, networkservice, and user values. Among them, LocalService has the lowest security and the user value has the highest security. You need a valid user account to install the service.

For the installer, you can also set its properties directly in the designer view.

The installer is directly built on the program concentration of the Windows service. After compilation, an EXE file will be created, for example, documentsexplorer.exe. Then, run the following command in command prompt mode of Visual Studio:
Installutil documentsexplorer.exe
You can install the service host.

Open the Service Control Manager (you can enter services. MSC in command prompt mode) and you can see the service named documentsexplorerservice:

Figure 3: Service Control Manager

If you want to uninstall the service host, you can uninstall it through the/u Switch of installutil.

In enterprise applications, we often set the Windows service to automatically start, which simplifies the work of administrators.

3. iis host (description, Here IIS is IIS 6.0)

To use the IIS host, you must add an SVC file to the Assembly. You can add an SVC file by adding a new project to the project:


Figure 4: add an SVC File

You can also directly create a WCF Service application as the IIS host, which automatically creates an SVC file, as shown in Figure 5:


Figure 5: Create a WCF Service Application

SVC File Created

Figure 6: created SVC File

The SVC File Created by the WCF Service Application and the SVC file obtained by adding a new project will automatically create the WCF Service. Therefore, this method can be used if you want to embed the code of the WCF Service in the SVC file. For example:


Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. runtime. serialization;
Using system. servicemodel;
Using system. text;
Using system. IO;

Using brucezhang. WCF. documentsexplorerdatacontract;

Namespace brucezhang. WCF. documentsexplorerserviceimplementation
[Servicebehavior (instancecontextmode = instancecontextmode. Single)]
Public class documentsexplorerservice: idocumentsexplorerservice
// Service implementation

In the above Code, the @ servicehost indicator can only be seen in view marckup after right-clicking the SVC file.

The SVC file uses the @ servicehost indicator to specify the service to be hosted. In addition, it also specifies the language and call mode for implementing the service. You can also set codebehind to specify the service code. However, in IIS hosting, the Service Code or assembly file is limited. It can only be placed in one of the following locations:

(1) embedded code in the SVC file;
(2) place it in a separate set of programs registered in GAC;
(3) programs residing in the bin folder of the application (in this case, the bin Folder does not have to include );
(4) The app_code folder that resides in the ApplicationSource codeFile (based on the language settings, or C # Or VB ).

Even if we place the service code in the application root directory or other folders and specify the code path through codebehind, the service cannot be hosted.

If the service contract and service class are referenced in the Host application, we can directly create. A single file of SVC, and then include it to the hostservice in Step 6 under the application root directory. SVC. This file does not have an associated CS file. In this case, open the file directly in Visual Studio. Instead of writing service code, specify @ servicehost.

Note: In the preceding method, only servicehost instances can be created for the iis host. For custom servicehost instances, you must specify the factory class for creating custom servicehost through @ servicehost. For example, the custom servicehost and the corresponding factory class are as follows:



using system;
using system. servicemodel;
using system. servicemodel. activation;

namespace brucezhang. WCF. documentsexploreriishost
{< br> public class customservicehostfactory: servicehostfactory
{< br> protected override servicehost createservicehost (
type servicetype, Uri [] baseaddresses)
{< br> customservicehost =
New customservicehost (servicetype, baseaddresses);
return customservicehost;
}< BR >}

public class customservicehost: servicehost
{< br> Public customservicehost (type servicetype, Params URI [] baseaddresses)
: Base (servicetype, baseaddresses)
{< BR >}

protected override void applyconfiguration ()
{< br> base. applyconfiguration ();
}< BR >}

Then @ servicehost is changed:

In IIS-hosted applications, we need to create web. config (note that it is not app. config ). Section:


Name = "brucezhang. WCF. documentsexplorerserviceimplementation. documentsexplorerservice">
Contract = "brucezhang. WCF. documentsexplorerservicecontract.

Idocumentsexplorerservice "/>

Note that the configuration file here is slightly different from the previous host configuration file, that is, the base address of the service is not specified. This is because the address of the SVC file is automatically used as the base address of the service by IIS hosting. We cannot specify it in the configuration file. The SVC file address is the path set by the SVC file in the IIS virtual directory or site. For example, in IIS, create a virtual directory named documentsexplorer pointing to the iis host application documentsexploreriishost, as shown in 7:

Figure 7: create a virtual directory for IIS on the IIS Site

If the site property is not modified and the default port number and localhost are used, the base address of the Access Service is http: // localhost/documentsexplorer/hostservice. SVC. If you set the address to documentsservice in the service endpoint of the configuration file, for example:


Address = "documentsservice"
Binding = "basichttpbinding"
Bindingconfiguration = "documentexplorerservicebinding"
Contract = "brucezhang. WCF. documentsexplorerservicecontract. idocumentsexplorerservice"/>

The public service address is http: // localhost/documentsexplorer/hostservice. svc/documentsservic.

After the site is started through IIS, no operation is required. The service host automatically creates a servicehost instance or a custom servicehost instance specified by the factory.

Because the service address has changed, the client configuration file also needs to be modified accordingly. The service address must be set to the corresponding address. The base address of the service is the address of the SVC file in IIS.

The IIS host is a major service hosting method because it has multiple advantages, including ease of use, maintainability, security, and ease of deployment. However, it has a fatal hacker, that is, it only supports HTTP transmission binding. Especially in LAN scenarios, if you use an IIS host, you cannot use TCP transmission efficiency, or even use MSMQ and peerto peer for transmission.

The Windows activation Service (was) provided by IIS 7.0 (based on Windows Vista and Windows Server 2007) breaks through the HTTP dependency of IIS 6.0.

4. Was host

Was is part of IIS 7.0, but it can also be installed and configured independently. Was supports all available WCF transmission protocols, ports, and queues.

The methods for hosting services using was and IIS host are not much different. You still need to create an SVC file, and at the same time, you need to create a program in the site in IIS to direct to the hosted application, you can also set the service access alias and application pool.

Because was supports all bindings, Service binding is not restricted by the host.

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.