Microsoft WCF Hosting and Configuration

Exclusive offer: get 50% off this eBook here
Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications — Save 50%

Microsoft WCF 4.0 - Over 85 easy recipes for managing communication between applications with Microsoft Windows Communication Foundation 4.0 in this book and eBook

$29.99    $15.00
by Steven Cheng | October 2010 | Enterprise Articles Microsoft SOA

Windows Communication Foundation 4.0 (WCF 4.0) is a .NET-based application programming interface for building and running connected systems. It enables secure and reliable communication among systems within an organization or across the Internet.

In this article by Steven Cheng, author of the book Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications, we will cover:

  • Hosting a service in a console application
  • Hosting a service in Windows Service
  • Hosting a HTTP service with ASP.NET-compatible context
  • Hosting a non-HTTP service in IIS 7
  • Customizing IIS ServiceHost via ServiceHostFactory
  • Specifying a dedicated service instance for a singleton service
  • Hosting a service in WSS 3.0
        Read more about this book      

(For more resources on Microsoft, see here.)

Introduction

Service hosting and configuration is very important for building WCF services, especially at the service deployment stage. After developers complete the service development, we will need to deploy the service so as to make it available to all the client consumers. In the real world, there are various service deployment scenarios available, which will result in different deployment and configuration requirements on the service configuration or the hosting environment.

As an enhanced service development platform, WCF provides rich, built-in support on service hosting and configuration that can fulfill most of the existing deployment demands and requirements. For example, the most popular IIS hosting approach can provide high availability and stable service for local intranet or public internet-based deployment cases. The Windows service-hosting approach makes WCF service hosting easier to integrate with existing background scheduled tasks, and the self-hosting approach provides the most flexibility and customization points for service deployment in a production environment.

In this article, we will look at seven recipes on various WCF hosting and configuration scenarios. The recipes start with four typical hosting cases—self-hosting, Windows service hosting, IIS-based HTTP hosting, and IIS based non-HTTP hosting. This is followed by two customized service-hosting cases—including a custom ServiceHostFactory and a dedicated singleton-instance hosting. The last recipe demonstrates a more advanced WCF service-hosting scenario—Windows SharePoint Service hosting.

Hosting a service in a console application

When creating a simple demo program for .NET framework, we will probably choose a console application. At the same, when talking about WCF service hosting, the console-hosting scenario is the most convenient one, which is especially handy and useful when we want to do some quick demo or testing on some WCF functionality.

How to do it...

  1. Create a .NET framework-based Console project through Visual Studio.
    Visual Studio provides various project templates for creating a .NET framework-based application. For our sample console-hosting service here, we will choose the Console Application project type from the Visual Studio New Project wizard.

  2. Add a new WCF service into the project.
    We can simply accomplish this by using the Add New Item function in Visual Studio and choose WCF Service as the item type from Visual Studio's Add New Item UI.

  3. Add code into the Main function to start up the WCF service. The following code shows the typical Main function that starts up a WCF service in a console application: static void Main(string[] args)

    {
    using (ServiceHost consoleHost = new
    ServiceHost(typeof(TestService)))
    {
    consoleHost.Open();
    Console.WriteLine("press any key to stop service host...");
    Console.ReadLine();
    }
    }

How it works...

When you add a new WCF Service item in Visual Studio, the IDE actually helps you to finish the following three tasks:

  • Creating a ServiceContract interface.
  • Creating a Service class that implements the ServiceContract interface.
    The following code shows the sample ServiceContract and implementation class used in this recipe.

    [ServiceContract]
    public interface ITestService
    {
    [OperationContract]
    void DoWork();
    }
    public class TestService : ITestService
    {
    public void DoWork()
    {
    }
    }

  • Adding the service endpoint and binding configuration in the App.config file.

In addition to the Contract and service type, the IDE will also insert a default configuration setting for the endpoint that can be exposed through the service. The following screenshot shows the sample service configuration section that contains a single endpoint, which uses WSHttpBinding.

With the code and configuration entries as defined previously, we can start our service host by supplying the service type in the constructor of the ServiceHost class.

using (ServiceHost consoleHost = new
ServiceHost(typeof(TestService)))

What the runtime will do is, it will lookup the configuration file and load the <service> entry that has the name identical to the type specified in the constructor, and launch the service and endpoints defined in it.

The source code for this article can be found at http://www.packtpub.com/code_download/6034

Hosting a service in Windows Service

Windows Services are widely used on Windows operating systems for hosting applications that will perform some long-run or scheduled tasks in the background. Applications hosted via Windows Service can be running under a specific user account and can choose the startup mode (manually or automatically). As a popular service-application-hosting scenario, it is also quite common to deploy a WCF service as a Windows Service.

How to do it...

In this recipe, we will use a typical .NET-based Windows Service to demonstrate how to host a WCF service in a Windows Service application. Let's go through the detailed steps:

  1. Create a Windows Service project.
    The first step is to create a new Windows Service project through the Visual Studio IDE. When creating the project, we simply choose the Windows Service project type. The following screenshot shows how we can select the Windows Service project type in the Visual Studio New Project wizard.

  2. Add a new WCF service item.
    As a WCF service hosting application, we certainly need to have a WCF service defined here. The steps for creating a WCF service are the same as what we've discussed in the Hosting a service in console application recipe.
  3. Add service hosting code into the service startup and shutdown event.
    As for the service-hosting code in the Windows Service, we need to put it in the correct place, since the .NET-based Windows Service type doesn't directly expose the Main function. The following code shows how the WCF service startup and shutdown code is defined:

    public partial class Service1 : ServiceBase
    {
    ServiceHost _svcHost = null;

    protected override void OnStart(string[] args)
    {

    // Start the service host here
    _svcHost = new ServiceHost(typeof(TestService));
    _svcHost.Open();
    }

    protected override void OnStop()
    {
    // Close the service host
    _svcHost.Close();
    }
    }

  4. Add an installer for the Windows Service.
    Now the Windows Service class and WCF service types have been defined. However, we still need to add another component—the installer class for deploying the Windows Service into the Windows Service collection on the target operating system. In the Visual Studio IDE, we can simply add an installer type for the Windows Service by the context menu on the component designer. The following screenshot shows the context menu item for creating the installer class for the Windows Service.

    The IDE will help create two helper classes—one is of ServiceProcessInstaller type and another of ServiceInstaller type. We can specify many deployment parameters for the Windows Service in the Property panel of the two classes. The following screenshot shows the properties of the sample serviceProcessInstaller1 class.

    The next screenshot shows the properties of the sample serviceInstaller1 class.

    As with the screenshots displayed, Visual Studio will use standard Properties windows for displaying and configuring the individual properties of the Windows Service classes.

  5. Install the Windows Service through Installutil.exe.
    The last step is to install the Windows Service we have created (after building the project) into the operating system. This can be done by using the Installutil.exe tool provided by the .NET framework. You can directly execute the Installutil.exe command within the Visual Studio command-line prompt window or you can choose to launch the tool through its absolute path in the .NET framework folder such as C:\ Windows\Microsoft.NET\Framework\v4.0.30319.

    The following statements show the complete commands for installing and uninstalling a .NET-based Windows Service application via the Installutil. exe tool.
    Install the Windows Service:
    InstallUtil.exe WCFNTService.exe
    Uninstall the Windows Service:
    Install Util.exe /u WCFNTService.exe
    The WCFNTService.exe mentioned earlier is the output assembly name of the sample Windows Service project.

How it works...

The OnStart event is fired when the Windows Service is starting, while the OnStop event is fired when the Windows Service is shutting down. Therefore, they are the best places for us to put the WCF service-hosting code.

Sometimes, we may need to access some remote or protected resource in our Windows Service host program. In such cases, it is important to specify a proper service account, either at development time or in the Windows Service Configuration Manager. The following screenshot shows the service list, which contains the installed sample Windows Service in Windows Service Configuration Manager.

See also

  • Hosting a service in a console application
Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications Microsoft WCF 4.0 - Over 85 easy recipes for managing communication between applications with Microsoft Windows Communication Foundation 4.0 in this book and eBook
Published: October 2010
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on Microsoft, see here.)

Hosting a HTTP service with ASP.NET-compatible context

ASP.NET provides a powerful platform for developing web applications over the .NET framework. An ASP.NET web application is also a natural hosting environment for a WCF service over the web HTTP protocol, which means developers can deploy WCF services with ASP.NET web pages in the same web application side by side without any particular effort.

However, by default, some ASP.NET runtime features or state objects are not available to WCF service code even if they are within the same web application. Those limited features include:

  • HttpContext is always null when accessed from within a WCF service.
  • Configuration-based URL Authorization (via <authorization> configuration element) is not available to WCF .svc files. These settings are ignored for WCF requests if a service resides in a URL space secured by ASP.NET's URL authorization rules.
  • Custom HttpModules injected into an ASP.NET application to intercept requests at later stages of the pipeline do not intercept WCF requests.
  • ASP.NET-specific states such as sessionState and Application Cache are not available to WCF service codes.

Then, how can we make such features accessible to a WCF service again? Well, the WCF-service hosting infrastructure has provided a feature called ASP.NET Compatibility Mode, which can help resolve the problem. This feature is by default disabled; we will show you how to enable this feature so that the WCF service continues to enjoy the ASP.NET runtime in this recipe.

How to do it...

  1. The first thing we need to do is get an existing ASP.NET web application and then add a new WCF service into the web application. For our sample case, we will use an empty ASP.NET website with two simple ASPX pages as the hosting website. Then, a WCF service named EchoService.svc will be added into it so that the two ASPX web pages can run side by side with the EchoService.svc service. The following screenshot shows the web application structure in Visual Studio Solution Explorer.

    The EchoService has a very simple ServiceContract, which contains a single Echo operation to return some data of type String (refer to the following code snippet).

    [ServiceContract]
    public interface IEchoService
    {
    [OperationContract]
    string Echo();
    }

  2. Now we have the ASP.NET web pages and WCF service hosting together. However, the WCF service code still cannot access those ASP.NET-specific runtime objects yet. What we need to do is apply ASP.NET Compatibility Mode into the hosting web application and the WCF service deployed in it.
    To enable ASP.NET Compatibility Mode, we can simply set the aspNetCompatibilityEnabled attribute to true in the <serviceHostingEnvironment> setting of the WCF configuration section. The following screenshot shows the configuration fragment with ASP.NET Compatibility Mode enabled.

    On the service implementation class of the WCF service, we need to apply the System.ServiceModel.Activation.AspNetCompatibilityRequirements attribute and set the RequirementsMode property to AspNetCompatibilityRequirementsMode.Allowed. This is quite useful, since sometimes we might not want certain WCF services to gain access to those ASP.NET runtime context objects, even if the hosting web application has ASP.NET Compatibility Mode enabled. The following code snippet shows the implementation class of the sample EchoService, which has applied the proper AspNetCompatibilityRequirements setting:

    using System.ServiceModel.Activation;

    [AspNetCompatibilityRequirements(
    RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed
    )]
    public class EchoService : IEchoService
    {

    }

  3. Having all the services and applications configured appropriately, we can now start enjoying the ASP.NET context objects within the WCF service code. The following code snippet shows the sample Echo operation code, which collects several runtime properties from the ASP.NET request context and returns them to the service caller:


    public class EchoService : IEchoService
    {
    public string Echo()
    {
    var approot = HttpContext.Current.Server.MapPath("~/");
    var data = HttpContext.Current.Cache["key1"];
    var url = HttpContext.Current.Request.RawUrl;

    return string.Format("{0}, {1}, {2}", approot, data, url) ;
    }
    }

    By performing a quick test on the WCF service in the WCF Test Client tool, we can get the expected response with all the ASP.NET context properties returned, as shown in the following screenshot:

How it works...

WCF HTTP services hosted in an ASP.NET web application can be run in two different modes— the default mode and ASP.NET Compatibility Mode.

In the default mode, the ASP.NET runtime intercepts the WCF request in the early stage of the pipeline: BeginRequest (one of the interception points of ASP.NET HttpModule), so most of the ASP.NET Context information is not available to the WCF service code. When ASP.NET Compatibility Mode is enabled on the WCF service, the WCF service runtime hooks up into the ASP.NET HTTP pipeline through both module and handler for the HTTP transport, so those ASP.NET-specific context data become available again.

There's more...

For more detailed information about ASP.NET Compatibility Mode for WCF service hosting, you can refer to the following article from Wenlong Dong's Blog:

Hosting a non-HTTP service in IIS 7

Since Windows 2003 Server, IIS is increasingly playing a more important role in the Windows Server operating system (for deploying server applications that will need to expose HTTPbased endpoints for client consumers). And IIS host is also a popular deployment scenario for a WCF service application. However, starting from IIS 7, the new process activation model (Windows Activation Service) provides non-HTTP support also, which makes deploying non- HTTP endpoint-based WCF services also possible.

How to do it...

  1. Install WCF non-HTTP activation components on the host machine.
    Though IIS 7 supports hosting non-HTTP-based WCF service endpoints, we need to make sure the WCF Non-HTTP Activation Components are correctly installed on the hosting server. The following MSDN reference provides detailed steps on installing the WCF Non-Http Activation Components:
  2. Configure the hosting IIS site and application virtual directory to enable non-HTTP binding support.
    After installing the activation components, we need to enable a certain type of binding in a particular IIS site and application virtual directory, in which our WCF service will deploy. In our sample WCF service, we will use NetTcpBinding. Therefore, we will add a net.Tcp binding into the IIS default site. This can be done through the Edit Bindings wizard in IIS7's manager tool. The next screenshot shows how we can launch the Edit Bindings configuration wizard against a particular IIS site in the manager tool.

    Also, we need to enable the binding protocol at individual virtual directory level (refer to the following screenshot). This will give developers and administrators more flexible granularity of control over multiple applications deployed in the same IIS site.

  3. Create a WCF service in the web application.
    Like hosting a normal HTTP-based WCF service in a web application, we need to add a .svc file and configure it to use a certain WCF service type (see the following directive).

    <%@ ServiceHost Language="C#" Debug="true" Service="ServiceLib.
    CalcService,ServiceLib, Version=1.0.0.0, Culture=neutral, PublicKe
    yToken=3d43fe2725af75c2" %>

    However, the most important thing here is to make our WCF service use the correct non-HTTP binding and address. In the sample service here, our CalcService service will use NetTcpBinding and the endpoint address will use the TCP port (8099) we added in step 2. The following screenshot shows the detailed endpoint configuration.

How it works...

In the previous sample service, we add a MexTcpBinding-based endpoint in addition to the main service endpoint. This MexTcpBinding endpoint is used for a client application to acquire the metadata of the service. If you use the Visual Studio Add ServiceReference command to generate the proxy, you can directly type the metadata address in the metadata browser's address bar.

Customizing IIS ServiceHost via ServiceHostFactory

When hosting in an IIS server, the WCF service and endpoints configuration are, by default, loaded from the Web.config file. So, developers do not need to explicitly create and initiate the ServiceHost like we do in a self-hosting scenario. Sometimes, however, we still need to customize the service or endpoints through code. This recipe will use a custom metadata configuration case to demonstrate how to programmatically adjust service behaviors in an IIS-hosting scenario.

How to do it...

Here we will go through the steps of applying a customized ServiceMetadataBehavior into an IIS-hosted WCF service:

  1. Create the WCF service in the hosting web application.
    We can simply create a new WCF service by adding a new WCF Service item in the hosting web application. The resulting WCF service is represented by a .svc file and an optional code-behind file (the CalcService.svc and CalcService.svc.cs files shown in the following screenshot).

  2. Define a custom ServiceHostFactory class for customizing the metadata configuration.
    As what we want to do is customize the metadata configuration, we should override the CreateServiceHost method and inject our custom code logic there. The following code snippet shows a sample implementation of the custom ServiceHostFactory.

    public class CustomConfigServiceHostFactory : ServiceHostFactory
    {
    protected override System.ServiceModel.ServiceHost
    CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
    ServiceHost host = base.CreateServiceHost(serviceType,
    baseAddresses);
    // Configure service behaviors here
    ServiceMetadataBehavior smb =
    host.Description.Behaviors.Find<ServiceMetadataBehavior>();
    if (smb == null)
    {
    smb = new ServiceMetadataBehavior();
    host.Description.Behaviors.Add(smb);
    }
    smb.HttpGetEnabled = true;
    smb.HttpGetUrl = new
    Uri("http://localhost:10394/CalcService.svc/wsdl");

    return host;
    }
    }

    As we can see, the CreateServiceHost method locates the ServiceMetadataBehavior from the ServiceHost instance (created automatically by the web application runtime) and adjusts the metadata properties.

  3. Apply the custom ServiceHostFactory to the target service.
    In order to apply our custom ServiceHostFactory, we can use the Factory attribute on the @ServiceHost directive in the .svc file as shown in the following code snippet:

    <%@ ServiceHost Language="C#" Debug="true" Service="ServiceWebApp.
    CalcService" CodeBehind="CalcService.svc.cs"
    Factory="CustomConfigServiceHostFactory" %>

How it works...

Though we do not explicitly create the ServiceHost instance, when the first client request reaches the IIS server, the WCF Service Activation module will help load the ServiceHostFactory specified in the .svc file. This Activation module is added in the machine.config file when installing the .NET 3.0 framework, as shown in the following configuration fragment.

So, this activation model provides the opportunity for developers to inject their own code logic into the ServiceHost by supplying a custom ServiceHostFactory type. Also, if you do not explicitly specify the ServiceHostFactory, the runtime will use a default factory to create the ServiceHost.

See also

  • Hosting a non-HTTP service in IIS 7

Specifying a dedicated service instance for a singleton service

Normally, when hosting a WCF service, we only need to specify the service type in the ServiceHost and the runtime will help create the service instance internally, according to the InstanceContextMode we apply on the service class. This makes hosting a WCF service quite simple and convenient; the service developers do not need to know when and how the runtime creates the service instance. However, in some cases, it is useful and necessary to let the developer control when and how the service instance is created.

Getting ready

Singleton is one of the popular design patterns. This pattern can help design a class that will expose one and only one instance of the class over the entire lifecycle of the class or application context. This is very useful in cases where we want to restrict the number of instances of a given class or component.

How to do it...

In this recipe, we will use a sample Voting service to demonstrate how to supply a dedicated service instance for a WCF service hosting in singleton mode. The hosting environment can manipulate and communicate with the service instance directly throughout the hosting lifetime.

  1. Define the ServiceContract and implement the service with special properties.
    The sample voting service contains a single operation Vote. This is used by the client to submit a vote request for a certain item. The following code shows the complete ServiceContract and implementation of the VotingService:

    [ServiceContract()]
    public interface IVotingService
    {
    [OperationContract]
    void Vote(string name);
    }
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.
    Single)]
    public class VotingService : IVotingService
    {
    private object _syncobj = new object();
    private Dictionary<string, int> _votelist = new
    Dictionary<string, int>();

    public void Vote(string name)
    {
    lock (_syncobj)
    {
    if (!_votelist.ContainsKey(name)) _votelist.Add(name, 0);
    _votelist[name] = _votelist[name] + 1;
    }
    }

    public KeyValuePair<string, int>[] GetVoteList()
    {
    return _votelist.ToArray<KeyValuePair<string, int>>();
    }

    }

    Note that in the implementation class (type VotingService), we add an additional member function called GetVoteList. This function is not a WCF service operation and is used for the service hosting program to query the current voting status list.

  2. Create the service instance and supply it to the ServiceHost.
    The next step, also the most important step, is to tell the WCF ServiceHost to use the service instance created by our code. For the sample VotingService, we simply create the service instance and assign it to the ServiceHost in the constructor as shown in the following code:

    ServiceHost host = null;
    try
    {
    _serviceInstance = new VotingService();
    host = new ServiceHost(_serviceInstance);
    host.Open();
    string input = "";
    while (input != "exit")
    {
    // Print voting list
    Console.WriteLine("name: voting count");
    foreach (var pair in _serviceInstance.GetVoteList())
    {
    Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
    }
    Thread.Sleep(1000 * 3);
    input = Console.ReadLine();
    }
    }
    finally
    {
    host.Close();
    }

    Similar to using a service type name, the constructor here (which takes an instance object) will also correctly load the service configuration from the App.config file.

How it works...

WCF allows developers to control how the service instance objects are created, and the relation between service instance and client channel through the ServiceContractAttribute.InstanceContext property. The following table shows every possible InstanceContextMode along with its description.

InstanceContextMode

Description

PerSession

A new InstanceContext object is created for each session.

PerCall

A new InstanceContext object is created prior to, and recycled subsequent to, each call. If the channel does not create a session, this value behaves as if it were PerCall.

Single

Only one InstanceContext object is used for all incoming calls and is not recycled subsequent to the calls. If a service object does not exist, one is created. Note that for singleton lifetime behavior (for example, if the host application calls the ServiceHost constructor and passes an object to use as the service), the service class must set InstanceContextMode to InstanceContextMode. Single, or an exception is thrown when the service host is opened.

For our sample service here, we use the Singleton mode so as to make our WCF service expose a single service instance object to process client requests. However, only applying the InstanceContextMode.Singleton is not enough, since we also need to control the creation of the service instance object. Therefore, we also add code to manually create the service instance object and supply it into the ServiceHost via the constructor.

By supplying a dedicated service instance object, we can conveniently communicate with the service instance in the hosting code. For example, in the above sample voting service, the console service host can query the voting count at any time by accessing the public methods for properties on the service instance type.

There's more...

For more information about the Singleton design pattern, you can refer to the following page:

Hosting a service in WSS 3.0

ASP.NET ASMX Web Service is naturally supported in WSS 3.0, and developers can also write their own Web Services and deploy them into WSS 3.0 servers and sites. With the WCF coming in .NET Framework 3.0, people are also interested in how to deploy their custom WCF service into WSS 3.0 sites.

How to do it...

  1. Creating the WCF service.
    The sample service here is quite straightforward and contains a service operation that will return the current WSS site's URL (see the GetCurrentWebUrl function shown as follows):


    [ServiceContract]
    public interface ISimpleWSSService
    {
    [OperationContract]
    void DoWork();

    [OperationContract]
    string GetCurrentWebUrl();
    }

    Our sample service will use BasicHttpBinding without any requirement for authentication. The service configuration of the sample service is shown in the following screenshot.

    In the service configuration section, we have enabled aspNetCompatibilityEnabled so that our service code can access the object model of the ASP.NET/WSS hosting environment.

  2. Create a VirtualPathProvider for intercepting SVC endpoint requests in WSS.
    The next step is very important; we need to add a custom VirtualPathProvider for the WSS web application to correctly forward the SVC endpoint requests. The following code shows a very simple VirtualPathProvider implementation that will do the job:

    public class SVCVirtualPathProvider : VirtualPathProvider
    {

    public override bool FileExists(string virtualPath)
    {
    // Patches requests to WCF services: That is a virtual
    path ending with ".svc"
    string patchedVirtualPath = virtualPath;
    if (virtualPath.StartsWith("~", StringComparison.Ordinal)
    && virtualPath.EndsWith(".svc",
    StringComparison.InvariantCultureIgnoreCase))
    {
    patchedVirtualPath = virtualPath.Remove(0, 1);
    }
    return Previous.FileExists(patchedVirtualPath);
    }
    }

    The FileExits function is the only one where we need to add customized code; our implementation simply checks whether the request is coming for a .svc extension. If it is an SVC request, remove the ~ char from the URL and continue the execution. In addition, we need to create a custom HttpModule that is responsible for registering the custom VirtualPathProvider into the WSS runtime. The following code shows this HttpModule used in our sample service:

    public class SVCVirtualPathProviderModule : IHttpModule
    {
    static bool _inited = false;
    static object _syncobj = new object();
    ...

    public void Init(HttpApplication context)
    {
    if (!_inited)
    {
    lock (_syncobj)
    {
    if (!_inited)
    {
    SVCVirtualPathProvider svcVPP = new
    SVCVirtualPathProvider();
    HostingEnvironment.RegisterVirtualPath
    Provider(svcVPP);

    _inited = true;
    }
    }
    }
    }

    }

  3. Deploying the WCF SVC endpoint into a WSS web application.
    For our sample service, we will deploy it into the WSS LAYOUTS folder. We will create a sub directory so as to make the structure look more clear. The complete path of the directory in which we deploy our WCF service is C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\ MyCustomApp.
    There are two things that we need to add into the deploying directory—one is the .svc service file, and the other is the web.config file that contains the service configuration entries.

    Another thing we need to do here is to install the service assembly (including the VirtualPathProvider components) into the system GAC (Global Assembly Cache) so that the WSS hosting runtime can correctly locate them. The assembly name is also referenced in the .svc service file, as shown in the following code:

    <%@ ServiceHost Service="WSSSVCLib.SimpleWSSService, WSSSVCLib,
    Version=1.0.0.0, Culture=neutral, PublicKeyToken=d5ae877ce0946ee3"
    %>

  4. Configuring the WSS web application to enable WCF endpoints.
    After deploying our WCF service into the target WSS application folder, we still need to apply some further changes so as to make the WSS environment WCF-enabled. These preparations include:
    • Enabling anonymous access on the virtual directory that contains our WCF SVC service files. We can enable anonymous access for our specific MyCustomApp directory through the IIS management console.
    • Registering the custom VirtualPathProvider in the WSS web application. As we use a custom HttpModule to register the custom VirtualPathProvider, we need to add our custom HttpModule into the WSS web application's web.config file. The following screenshot shows the sample web.config section that registers our HttpModule.

How it works...

In our WSS service hosting sample, we created a custom VirtualPathProvider for intercepting the .svc requests coming into the WSS web application. This is necessary, since the WSS 3.0 runtime will raise a path-processing exception if we do not manually intercept the request and alter the original path. The following screenshot shows the error page if we deployed a WCF service in a WSS 3.0 web application without configuring a custom VirtualPathProvider.

After the WCF service is correctly deployed in the WSS web application, we can use a web browser to visit the default metadata page like a normal SVC service.

Summary

This article covered several common and useful WCF service-hosting scenarios, such as hosting a WCF service in a Windows service, IIS web applications, and a WSS 3.0 site.


Further resources on this subject:


Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications Microsoft WCF 4.0 - Over 85 easy recipes for managing communication between applications with Microsoft Windows Communication Foundation 4.0 in this book and eBook
Published: October 2010
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Steven Cheng

Steven Cheng is a senior support engineer at Microsoft Global Technical Support Center where he has been supporting Microsoft software development technologies for more than 5 years. Currently, as a community leader, he is working actively in the MSDN newsgroup and forum communities.

Steven Cheng's technical specialties cover many popular areas of Microsoft development technologies including .NET framework, ASP.NET, XML WebService, Windows Communication Foundation, SharePoint development, and so on. His blog can be found at http://blogs.msdn.com/stcheng.

Books From Packt


Microsoft Windows Workflow Foundation 4.0 Cookbook
Microsoft Windows Workflow Foundation 4.0 Cookbook

WCF 4.0 Multi-tier Services Development with LINQ to Entities
WCF 4.0 Multi-tier Services Development with LINQ to Entities

Microsoft SQL Server 2008 High Availability
Microsoft SQL Server 2008 High Availability

WS-BPEL 2.0 for SOA Composite Applications with IBM WebSphere 7
WS-BPEL 2.0 for SOA Composite Applications with IBM WebSphere 7

Microsoft Azure: Enterprise Application Development
Microsoft Azure: Enterprise Application Development

Least Privilege Security for Windows 7, Vista and XP
Least Privilege Security for Windows 7, Vista and XP

Microsoft Dynamics NAV Administration
Microsoft Dynamics NAV Administration

Service Oriented Architecture: An Integration Blueprint
Service Oriented Architecture: An Integration Blueprint


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
3
S
i
q
u
F
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software