WCF - Hosting
As we already know, WCF - Windows Communication Foundation - is an integral part of the NET Framework 3.0. It provides a set of classes for building and hosting services based on SOA architecture ( Service Oriented Architecture ), may expose such services to be accessed through various types of protocols such as: HTTP, TCP, IPC and MSMQ. Currently there are three types of hosts for services built on WCF: self-hosting (through the classServiceHost ), IIS ( Internet Information Services ) and WAS ( Windows Activation Services - Windows Vista), and this is exactly what this article will address, namely , how to configure each of these hosts to expose services built on WCF. As the focus of the article is exclusively setup host , I will consider how prior knowledge the procedure for creating basic WCF service, especially with regard to the attributes that should be applied to the service to make it a WCF service. For example, let's create a standard contract, called IServiceContract , which will be implemented by concrete services. This contract (one interface ) will have two simple methods, called BoasVindas and HoraAtual. This interface is shown below:
The self-hosting is an application, be it Console, Windows Forms, Windows Service, etc., that exposes one or more services to be consumed by their customers. To be able to expose the service programmatically, ie without using IIS or WAS, it is first necessary to reference the file System.ServiceModel.dll . This assembly contains all necessary to work with Windows Communication Foundation classes - WCF - and also provides the classServiceHost . This class provides the necessary infrastructure to expose WCF services. One of the overloads of the constructor of the class ServiceHost receives an object of type Type , which should point out which is the type that the host will expose. Then you must set the endpoint to indicate where and with what protocol the service will be exposed and to meet this need, the class ServiceHost provides one method called AddServiceEndpoint how to create endpoints are necessary for the service. The class ServiceHost still provides some events that may be useful for monitoring purposes. These events are described in the table below:
IIS - Internet Information Services
to launch the WCF had (and still have) available within the NET platform, the ability to build the famous Web Services (ASMX). Web services have been launched since version 1.0 of the NET Framework and revolutionized the way how to expose data and components for consumption. They, in turn, are strongly linked to the architecture of ASP.NET, where the dependence of the HTTP protocol and some of its specific features are one of the "worst" parts, since it breaks some of the concepts that SOA requires. services WCF can also use IIS as hosting , very similarly to the Web Services (ASMX) form, taking some of the same income; a key is the activation process, which is done when a request comes to the server. But not everything is perfect, IIS limits the type of transportation, forcing us to use only the HTTP protocol. To be able to do the host a service in IIS, you need to have a physical file with the .svc extension *. This file type is associated with a WCF service and when the request for an appeal reaches the server, it is treated through a module called HttpModule in conjunction with a handlercalled HttpHandler , which are contained within the namespace System. ServiceModel.Activation (this can be confirmed through the file Web.Config that is within the following address: % windir% \ Microsoft.NET \ Framework \ v2.0.50727 \ CONFIG ). The way these objects work will depend on the compatibility mode with ASP.NET which may or may not be enabled. Further analyze the two existing methods, this article yet. 's file with extension * .svc has a directive ServiceHost where we inform the language that will be writing the code, the service name and the path to the file CodeBehind service, which lies within the special folder App_Code . This is very similar to the structure of an ASP.NET page. The code below shows the structure of only one line of a file * .svc:
WAS - Windows Activation Services
Windows Vista provides a new feature called WAS - Windows Activation Services. It is a process that is installed within IIS 7, which decouples the activation architecture of IIS, allowing transport not only via HTTP, but also vianamed pipes , TCP and MSMQ ( message queue ). Another important point is that, in addition to supporting multiple protocols, provides the functionality provided by IIS, such as health monitoring , process recycling and consequently management tools for such settings. When the listener of a certain protocol receives the request, WAS checks the work process and to serve him, before processing the request, the handler ensures that an instance of the class ServiceHost has been created. As we saw in IIS, WAS fortunately also uses the activation model based on the message, which increases scalability for requests in any protocol. WAS by default it is not installed by default. You need to make some adjustments to enable it and consequently provide WCF service to be consumed in various protocols. Leave the configuration and use of WAS in IIS 7 (Windows Vista) for a future article, dedicating it to fully exploit this new feature. Conclusion : As you can see throughout this article, the entire host basically should be an executable process which will have a AppDomain where the service will be charged. Now, with all these alternatives, you should analyze and be able to choose which of the solutions is more feasible to your needs, always weighing the pros and cons of each type of host .
using System;
using System.ServiceModel;
namespace DevMinds.ComponentCS
{
[ServiceContract]
public interface IServiceContract
{
[OperationContract]
BoasVindas string ();
[OperationContract]
DataAtual DateTime ();
}
}
|
The self-hosting is an application, be it Console, Windows Forms, Windows Service, etc., that exposes one or more services to be consumed by their customers. To be able to expose the service programmatically, ie without using IIS or WAS, it is first necessary to reference the file System.ServiceModel.dll . This assembly contains all necessary to work with Windows Communication Foundation classes - WCF - and also provides the classServiceHost . This class provides the necessary infrastructure to expose WCF services. One of the overloads of the constructor of the class ServiceHost receives an object of type Type , which should point out which is the type that the host will expose. Then you must set the endpoint to indicate where and with what protocol the service will be exposed and to meet this need, the class ServiceHost provides one method called AddServiceEndpoint how to create endpoints are necessary for the service. The class ServiceHost still provides some events that may be useful for monitoring purposes. These events are described in the table below:
|
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using DevMinds.ComponentCS;
static void Main (string [] args)
{
using (ServiceHost host = new ServiceHost (typeof (DefaultService)
new Uri ("net.tcp: // localhost: 9000 /")))
{
host.Description.Behaviors.Add (new ServiceMetadataBehavior ());
host.AddServiceEndpoint (
typeof (IMetadataExchange)
MetadataExchangeBindings.CreateMexTcpBinding ()
"MEX /");
host.AddServiceEndpoint (
typeof (IServiceContract)
new NetTcpBinding (),
"DefaultService /");
host.Open ();
Console.ReadLine ();
}
}
|
<? Xml version = "1.0" encoding = "utf-8"?>
<Configuration>
<System.serviceModel>
<Services>
<Service name = "DevMinds.ComponentVB.DefaultService" behaviorConfiguration = "MEX">
<Host>
<BaseAddresses>
<Add baseaddress = "net.tcp: // localhost: 9000 /" />
</ BaseAddresses>
</ Host>
<Endpoint
contract = "IMetadataExchange"
binding = "mexTcpBinding"
address = "MEX /" />
<Endpoint
contract = "DevMinds.ComponentVB.IServiceContract"
binding = "netTcpBinding"
address = "DefaultService /" />
</ Service>
</ Services>
<Behaviors>
<ServiceBehaviors>
<Behavior name = "MEX">
<ServiceMetadata />
</ Behavior>
</ ServiceBehaviors>
</ Behaviors>
</system.serviceModel>
</ Configuration>
|
IIS - Internet Information Services
to launch the WCF had (and still have) available within the NET platform, the ability to build the famous Web Services (ASMX). Web services have been launched since version 1.0 of the NET Framework and revolutionized the way how to expose data and components for consumption. They, in turn, are strongly linked to the architecture of ASP.NET, where the dependence of the HTTP protocol and some of its specific features are one of the "worst" parts, since it breaks some of the concepts that SOA requires. services WCF can also use IIS as hosting , very similarly to the Web Services (ASMX) form, taking some of the same income; a key is the activation process, which is done when a request comes to the server. But not everything is perfect, IIS limits the type of transportation, forcing us to use only the HTTP protocol. To be able to do the host a service in IIS, you need to have a physical file with the .svc extension *. This file type is associated with a WCF service and when the request for an appeal reaches the server, it is treated through a module called HttpModule in conjunction with a handlercalled HttpHandler , which are contained within the namespace System. ServiceModel.Activation (this can be confirmed through the file Web.Config that is within the following address: % windir% \ Microsoft.NET \ Framework \ v2.0.50727 \ CONFIG ). The way these objects work will depend on the compatibility mode with ASP.NET which may or may not be enabled. Further analyze the two existing methods, this article yet. 's file with extension * .svc has a directive ServiceHost where we inform the language that will be writing the code, the service name and the path to the file CodeBehind service, which lies within the special folder App_Code . This is very similar to the structure of an ASP.NET page. The code below shows the structure of only one line of a file * .svc:
[C #]
<% @ ServiceHost Language = "C #"
Debug = "true"
Service = "DefaultService"
CodeBehind = "~ / App_Code / DefaultService.cs"%>
|
<? Xml version = "1.0">
<Configuration>
<System.serviceModel>
<Services>
<Service name = "DefaultService" behaviorConfiguration = "returnFaults">
<Endpoint
contract = "DevMinds.ComponentCS.IServiceContract"
binding = "wsHttpBinding" />
</ Service>
</ Services>
<Behaviors>
<ServiceBehaviors>
<Behavior name = "returnFaults">
<ServiceDebug includeExceptionDetailInFaults = "true" />
<ServiceMetadata httpGetEnabled = "true" />
</ Behavior>
</ ServiceBehaviors>
</ Behaviors>
</system.serviceModel>
</ Configuration>
|
![]() |
Figure 1 - Output of the service being invoked in the browser. |
|
|
using System.ServiceModel.Activation;
[AspNetCompatibilityRequirements (
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DefaultService: IServiceContract
{
// Remainder of implementation
}
|
<? Xml version = "1.0">
<Configuration>
<System.serviceModel>
<ServiceHostingEnvironment aspNetCompatibilityEnabled = "true" />
<Services>
<Service name = "DefaultService">
<- Endpoints ->
</ Service>
</ Services>
<- Other Settings ->
</system.serviceModel>
</ Configuration>
|
WAS - Windows Activation Services
Windows Vista provides a new feature called WAS - Windows Activation Services. It is a process that is installed within IIS 7, which decouples the activation architecture of IIS, allowing transport not only via HTTP, but also vianamed pipes , TCP and MSMQ ( message queue ). Another important point is that, in addition to supporting multiple protocols, provides the functionality provided by IIS, such as health monitoring , process recycling and consequently management tools for such settings. When the listener of a certain protocol receives the request, WAS checks the work process and to serve him, before processing the request, the handler ensures that an instance of the class ServiceHost has been created. As we saw in IIS, WAS fortunately also uses the activation model based on the message, which increases scalability for requests in any protocol. WAS by default it is not installed by default. You need to make some adjustments to enable it and consequently provide WCF service to be consumed in various protocols. Leave the configuration and use of WAS in IIS 7 (Windows Vista) for a future article, dedicating it to fully exploit this new feature. Conclusion : As you can see throughout this article, the entire host basically should be an executable process which will have a AppDomain where the service will be charged. Now, with all these alternatives, you should analyze and be able to choose which of the solutions is more feasible to your needs, always weighing the pros and cons of each type of host .
To allow customers to extract the information (metadata) about the necessary service, we need to expose the description of it (which describes all the functionality provided by service endpoints and behavior) so that developers can reference it on the client applications that will consume it. You can expose this information via the HTTP protocol (via method Get ) or use an endpoint dedicated. The Windows Communication Foundation provides metadata automatically to the service through HTTP-GET, and later we will see how the contract available through other endpoints with different protocols. All you need to do is enable this by adding an explicit service behavior .summary, MEX ( metadata exchange endpoint ) is extremely necessary since the client needs to import locally have the service representation and consequently invoke it. For we configure a service to be exposed, we can do via code (Visual C # or Visual Basic .NET) or declaratively through the file * .Config application. As discussed above, a WCF service provides, by default, the description of it through the HTTP-GET protocol; but for this we need only enable it via the attribute httpGetEnabled element serviceMetadata , if we are talking about the configuration file via * .Config and if we want to expose the description via HTTP-GET. 's still the possibility of exposing the service description through an endpoint customized and can access it through another protocol, such as TCP. This scenario requires the creation of an endpoint simple, as I normally do for any service, but in this case, the type of contract to be exposed will be based on IMetadataExchange interface , which is defined within thenamespace System.ServiceModel.Description , which exposes methods that return metadata for the service. 'sendpoints (that expose the service and metadata) can be configured declaratively or programmatically. We will examine these two forms. For example purposes, we will use a project of type Console Application but a little later, we'll talk about the various applications that can serve as host for WCF service. The code below shows how to create code via the endpoint need to expose the service and another endpoint for MEX , both using TCP protocol:
As you can see, we create the instance of the class ServiceHost , stating in its constructor the type that it will serve and what address will make it available. We then add an instance of class ServiceMetadataBehavior within a collection called Behaviors related to host newly created; This step is necessary because the host validates the type of contract specified in the endpoints , ie, the contract of the endpoint must be compatible with the contract declared the creation of the ServiceHost . In the above case, the class we created, DefaultService , implements theinterface IServiceContract , but does not implement the interface IMetadataExchange . Internally when the hostdetects that the types are not compatible, it analyzes the behaviors that were recorded; if it finds an instance of the class ServiceMetadataBehavior only with her this you can add the endpoint metadata, which is already soon after. At this point, comes in a static class called MetadataExchangeBindings . This class provides static members that assist in creating bindings unique to each of the protocols, which will depend on the form of communication you want to have with customers to know which of these methods use. Same build up inside the file * .Config is the follows (note that the attribute contract element of the endpoint you must specify the interface of the service contract, including namespaces to it):
Note: It is important to say that the configuration file via * .Config not dispense object creation ServiceHost in the code and its opening by the method Open . The only difference here is that there is no need to inform thebaseaddress , behaviors and endpoints . With the host properly configured, regardless of whether it was through declarative code ( * .Config ) or via code, just start the application and at the address that was specified to create the service, you can add the reference in the client application and then longer be able to consume the service. As we mentioned above, the self-hosting allows one .NET application we use to make it available. There are three types of applications that can meet this need: Console Application (which we base our test), Windows Forms and Windows Service. The Console Application is very useful when we are performing tests or even in development time and is never given to the production environment, as it requires a user logged on the machine where the executable resides, and still can accidentally close the host , which would prevent subsequent requests are processed. The other option is to use create the host in a Windows Forms application. She is a little better about Console Application, but still requires a user to access the system in order to boot the host . Finally, we have the Windows Service. This indeed is one of the most appropriate types of applications to serve as host of a WCF service, as it requires the user to be logged in to work and yet can be configured to launch automatically when the computer is turned on. Regardless, the host should already be in the air when the request comes in, which does not happen with IIS, because it activates the object so that the request arrives at the server. Analyze the host via IIS in the next section.
Inside the file CodeBehind create a class and implement the interface IServiceContract (already mentioned above). After performed proper implementation due held, effectively defining what methods will do, you need to create the endpoint in the file Web.Config so that IIS can identify and expose the service. The configuration file is very similar to App.Config we saw above, that sets the service in a self-hosting . Slight changes are performed as shown below:
It is important to consider that the creation of the endpoint attribute is not necessary to address because the address ( base address ) will be determined from the address of the file * .svc. Another important detail is related to the attribute httpGetEnabled element serviceMetadata that, when set to True , is responsible for the contract to enable the service to be published, and consequently accessed by customers. Finally, the attributeincludeExceptionDetailInFaults , which is used for debugging purposes because, when set to True , propagates any exception thrown by the service to customers, facilitating debugging when we are consuming the service in a test environment. Of course this information should only be available when the service is still in the development process, because if this information reach the end customers, you may be opening it so that it can exploit the error information, including the stack trace . Invoking service in the browser, we now have access to it, even to their contract. The image below illustrates the service being rendered in the browser:
At this time the service is ready to be consumed by customers, and as we can see in the picture above, she herself displays an example of how to generate the proxy on the client, through the utility svcutil.exe or, if you are using Visual Studio. NET 2005 with NET Framework 3.0 installed properly, can go directly in the project where you want to consume the service, click the right mouse button on top of it and then click the option "Add Service Reference ..." , informing the above HTTP address, which automatically proxy will be generated and added to the application.quietly We can create a virtual directory in IIS to host WCF services. But there are scenarios where the WCF services are within IIS, but contained in an ASP.NET application or even an application of Web Services (ASMX) type. At all times, it is often necessary to use some specific features of the HTTP protocol to meet a particular need, such as the use of application variables ( Application ), session ( Session ) or even information in the context HTTP ( HttpContext ). WCF, together with the ASP.NET runtime provides two modes of execution of a request for a service, dealing very differently to the request * .svc. These forms are: Mixed Transports Mode orASP.NET Compatibility mode , which we'll talk then. At first, Mixed Transports Mode (default mode), the request of the service is not performed by the ASP.NET pipeline . This lets you define endpoints with different forms of transport. One of the most important features of this mode is that it allows WCF services to make use of specific features of ASP.NET, specifically the HTTP protocol. Among the features disabled by virtue of having enabled this way we have:
Already ASP.NET Compatibility Mode is a mode that enables all the restrictions imposed by the previous mode, but imposes a major negative point, ie, the service is completely dependent on the HTTP protocol and, therefore, when the service is activated , the endpoints will be checked to ensure that non-HTTP protocols are enabled. exists an element in the file Web.Config that allows us to declaratively enable or disable this mode. This is the attributeaspNetCompatibilityEnabled element serviceHostingEnvironment . When set to False (default), the method used is the Mixed Transports Mode and, when True , the way ASP.NET Compatibility Mode is enabled. But, the way to enable ASP.NET Compatibility Mode , you still need additional configuration, but this time directly in the class that represents and implements the service contract, which is to decorate the class with the attributeAspNetCompatibilityRequirements , which is contained within the namespace System.ServiceModel.Activationand configure it according to the need. This attribute is given by the property RequirementsMode , one of three values contained in the enumerator AspNetCompatibilityRequirementsMode , which are explained below:
The code snippets below, with some parts removed for reasons of space, illustrate the configuration in the class of service and the file Web.Config to enable ASP.NET Compatibility Mode :
Slightly above talked about the module HttpModule and HttpHandler handler , part of the execution of the processing of a request to a WCF service. The way to work will depend exclusively mode that is enabled. If the mode Mixed Transports is enabled, the module HttpHandler will intercept the request shortly after the eventPostAuthenticateRequest and, this time, the object HttpContext.Current is set to null. Now, when the modeASP.NET Compatibility is enabled, the module HttpModule is a simple filter, without doing anything more important. After execution of the module, the handler is finally executed, to effectively do the work of WCF service.
Comments
Post a Comment