12 de diciembre de 2014

Configuración de un servicio WCF

xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="serviceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="serviceBehavior" name="WcfServiceLibrary.Service1">
                <endpoint binding="ws2007HttpBinding" contract="WcfServiceLibrary.IService1" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost/WcfServiceApplication/Service1.svc" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>

¿No hay configuración? ¿Cómo es posible? Pues gracias a los Default Endpoints. Son endpoints “preconfigurados” que se cargan automáticamente para cada dirección base creada. Al llamarse al método Open del ServiceHost, ya sea automáticamente por parte de IIS o manualmente cuando se hostea el servicio en una aplicación de consola, se crean estos bindings predeterminados haciendo uso del método AddDefaultEndpoints. Un par de cuestiones a tener en cuenta:
  • Si se configura un endpoint en el fichero de configuración, ya no se hace efectiva la llamada a AddDefaultEndpoints.
  • Si aún así quisiéramos tener esos endpoints por defecto, siempre es posible llamar explícitamente al método AddDefaultEndpoints y añadir, a los endpoints definidos en el fichero de configuración, los que crea él por defecto.
Los bindings traen una configuración por defecto que se considera como más habitual. Por ejemplo, con una dirección base con protocolo http, el binding por defecto es basicHttpBinding. Esta nueva técnica ha sido bautizada como Default Protocol Mapping. En cualquier caso, este mapeo también es configurable; si quisiéramos que, por defecto, la direcciones con protocolo se resolvieran con un binding de tipo wsHttpBinding, sería necesario configurar lo siguiente en el app.config/web.config:
  <system.serviceModel>
    <protocolMapping>
      <add scheme="http" binding="wsHttpBinding"/>
    </protocolMapping>
  </system.serviceModel>
En este punto, tendríamos nuestro servicio hosteado en IIS. Nos quedaría activar los metadatos del servicio para generar el fichero WSDL y enviar información detallada en caso de error. Ambas no son configuraciones por defecto del servicio, por lo que tendríamos que editar el fichero app.config/web.config e introducir lo siguiente:
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
Si nos fijamos, veremos que no ha sido necesario ni darle un nombre al nuevo behavior del servicio, ni tampoco definir el servicio y asociarle el behavior, como hacíamos en 3.5. Esto se conoce como Default Behavior Configurations, configuraciones sin nombre que se van a aplicar a cualquier servicio que definamos. Tienen su contrapartida en los Default Binding Configurations, que realizan la misma función pero asociados a un tipo de binding.
Como se ha podido ver a lo largo del post, la configuración en WCF4, al menos la más habitual, se ha simplificado enormemente. Los nostálgicos de la sencillez de los servicios ASMX han perdido la principal razón para no dar el paso a WCF.
Now a question comes to mind, How is this done in WCF 4?
The answer to that is: When the host application calls the Open method on the ServiceHost instance, it builds an internal service description from the application configuration file. Then it checks the count of configured endpoints. If it is still zero then it will call the AddDefaultEndpoints public method and the method will add a default endpoint per base address for each service contract implemented by the service.
With WCF 4, it is possible to define the default behavior configurations for services and endpoints.
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

Endpoints will be mentioned in the web.config file on the created service.
<system.serviceModel>
<services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
       <endpoint
         address="http://localhost:8090/MyService/MathService.svc" contract="IMathService"
          binding="wsHttpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Binding and Behavior

Binding

Simple definition for Binding describes how the client will communicate with service. We can understand with an example.
Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.
<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
      <endpoint address="http://localhost:8090/MyService/MathService.svc" 
        contract="IMathService"
          binding="wsHttpBinding"/>
<endpoint address="net.tcp://localhost:8080/MyService/MathService.svc" 
contract="IMathService"
          binding="netTcpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

  
See how simple it is in WCF. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.

Example:

In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the servieMetadata node with attribute httGetEnabled='true'. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.
<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
        <endpoint address="" contract="IMathService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>