Hosting a WCF service in different hosting environments

Hosting a service is an important part of any service. Coming from web services, WCF exposes more relevant APIs to handle different kinds of hosting environments. A WCF service can be hosted virtually anywhere, starting from a simple Console Application, a Windows Service, IIS, or even other hosting services such as Windows Activation Service. After the service is hosted on an environment, the service endpoint for a particular service gets exposed. When the host process runs, WCF will be available using the configured endpoints.

Hosting a WCF service in different hosting environments

Any .NET application runs using a Windows process. Inside a process, you can host multiple .NET application domains. Each application domain logically separates the execution environment from another. WCF requires ServiceHost to host a worker process inside the application domain. Similarly, each application domain can host multiple worker processes. Each application represents service host-to-host multiple endpoints. In addition to that, WCF relies on the security and configuration features provided by an application domain. WCF, by default, uses the default identity of the process but you can impersonate the users too. Some of the hosting processes provide additional features. For instance, IIS provides automatic process recycling, resource throttling, logging, health indicators, and so on. Now, let's try out the different hosting environments in this recipe one by one to understand them further.

Getting ready

There are a number of ways to host a WCF service; one of them is in IIS. The latest version of IIS supports a number of endpoints, which can be used by the WCF service to host itself inside the IIS. As I have already mentioned, IIS gives you an edge while publishing your service inside it. Let's try IIS 7 to host our service.

IIS requires a physical file with a .svc extension to host the service properly. In our previous example, we already showed you how to host a service inside a console application using ServiceHost. The ServiceHost class is the class that creates the hosting environment for a service. If you are using IIS, you do not need to create an instance of ServiceHost because IIS automatically creates it for you. Let's create a web application and add a .svc file inside it.

How to do it...

Now let's create a WCF application to be hosted on different platforms:

  1. Start a web application and add a .svc file to the project.
  2. The SVC file template produces a ServiceHost server tag, which identifies that the IIS needs to create an object of ServiceHost and point to the appropriate service contract:
    <%@ ServiceHost Language="C#" Debug="true" Service="SVCHostingProject.MySample" CodeBehind="MySample.svc.cs" %>

    Here, the markup for the .svc file provides the ServiceHost implementation, which loads the service using the ServiceHost class automatically created by the ASP.NET pipeline inside IIS.

  3. After the service has been implemented, we need to configure the ServiceModel element of web.config with all the bindings that the service needs to support:
      <system.serviceModel>
          <services>
            <service name="SVCHostingProject.MySample">
              <endpoint name="basicHttpBinding"
                        address=""
                        binding="basicHttpBinding"
                        contract="SVCHostingProject.IMySample" />
              <endpoint name="mexHttpBinding"
                        contract="IMetadataExchange"
                        binding="mexHttpBinding"
                        address="mex" />
            </service>
          </services>
            <behaviors>
                <serviceBehaviors>
                    <behavior name="">
                        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                        <serviceDebug includeExceptionDetailInFaults="false" />
                    </behavior>
                </serviceBehaviors>
            </behaviors>
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
                multipleSiteBindingsEnabled="true" />
        </system.serviceModel>

    The preceding configuration provided two endpoints for the service; one with BasicHttpBinding, which is the default binding for any web application, and the mex binding, which is the metadata exchange for the service. Please note that we have left the Address attribute blank for the endpoint. As WCF can be hosted inside a virtual directory, the address is automatically handled by the IIS itself and there is no need for an address definition in configuration.

  4. Hosting a configuration also includes a special option to specify whether the service requires the ASP.NET compatibility mode. For instance, the service needing HTTP hosting may need the ASP.NET compatibility mode in configuration. To specify the ASP.NET compatibility mode for the service, we need to annotate the class with the AspNetCompatibilityRequirements attribute as follows:
    [AspNetCompatibilityRequirements(RequirementsMode= AspNetCompatibilityRequirementsMode.Required)]
    public class MySample : IMySample
    {
     
    }

    Marking the class with the ASPNETCompatibilityRequirements attribute will indicate that the class can run on ASP.NET compatibility.

  5. Finally, you can publish this website inside IIS by pointing the published directory to a virtual directory.
  6. If you are hosting inside ConsoleApplication/Windows Application/Windows Service, the only requirement that the application needs to make is to create an instance of the ServiceHost object.
  7. The ServiceHost class automatically creates hosting environments taking reference from the service configuration for the process automatically, and hosts the service inside it:
    ServiceHost host = new ServiceHost(typeof(MySample), new Uri("http://localhost:8080/MySample"));
    host.Open();

    Creating the host and opening it will host the service automatically inside the current application domain, and the ServiceHost class is capable of handling requests from the external environments. For any hosting environments, the host needs to be opened to start using the WCF service.

How it works...

The ServiceHost class is the primary type built inside the framework that hosts a WCF service. A WCF service is a contract-based model that is externally exposed using different types of endpoints supported by WCF. The ServiceHost class generally creates a SocketListener object inside it at a low-level to handle the requests from the external world. The call to open from ServiceHost is important as it opens up Listener on the port and the address specified for the service, and when any request is made to the address, it automatically spawns a new thread to handle the request.

The ServiceHost class automatically parses the incoming requests and dynamically creates the objects from the requests and calls the service logic. The ServiceHost class needs to call the close method when we want to release the service from memory.

There's more...

Let's consider a few more options for hosting.

What is Windows Process Activation Services (WAS)?

Hosting a WCF Service inside IIS is one of the most popular and well-accepted solutions worldwide. In IIS 5 or IIS 6, the solution of hosting a WCF service is strictly tied only to HTTP bindings. Even though WCF is very capable of hosting itself in other types of bindings that support a lower-level of interaction, there is no way to implement this in the previous version of IIS.

The WAS service enables hosting a service with any type of binding. IIS 7 implements a model called WAS, which takes on creating worker processes and providing generalized process activation and management.

Another important point to note is that even though WAS is a part of IIS 7, it can also be installed and configured separately. It is shipped with Windows Vista and Windows Server 2008.

When the first request comes for a service that is hosted on IIS 7, the listener adapter calls WAS to activate the worker process including the managed application domain for the specific application it is running on. As it does not matter whether the request is coming from ASP.NET or any other channel, once the process is activated for the current request, IIS handles the request automatically and retrieves the response and sends it back to the same channel. To start ServiceHost inside the application domain, the protocol handler calls the static method EnsureServiceAvailable, which will check and enable all service endpoints and transports.

To configure WAS for IIS, we need to edit the applicationHost.config file and add protocols for each binding element that needs to be supported:

<bindings>
<binding protocol="https" bindingInformation="*:443:" />
<binding protocol="http" bindingInformation="*:80:" />
<binding protocol="net.tcp" bindingInformation="808:*" />
<binding protocol="net.pipe" bindingInformation="*" />
<binding protocol="net.msmq" bindingInformation="localhost" />
<binding protocol="msmq.formatname" bindingInformation="localhost" />
</bindings>

You can also add the protocol bindings for a particular website using the appcmd.exe command.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.123.147