Thursday, April 25, 2013

WCF- Channel Factory


  • Channel Factory class used to create more than one channel which used by client to send a massage to service end points
  •  Channel Factory enables you to create a communication channel to the service without a proxy
  •  Channel Factory is implemented by the IChannelFactory Interface 

When to use a Channel Factory (shared DLL): 

Channel Factory is also useful when you do not share more than just the service contract with a client. If you know that your service contract will not change frequently than it is better to use a Channel Factory than a Proxy.
It makes good design sense to put service/data contracts in separate assemblies from service implementations. This way, you can safely distribute contract assemblies to third parties who wish to consume services, without the risk of disclosing their actual implementation.

The benefits of this approach include:
  • Less overall clutter in the client code.
  • More control over proxy wrapper code needed for the client to handle faulted channels and other customizations.
  • Clients and services share assemblies, thus are both immediately updated when changes are made.
  • Developers work with the same object model at the client and service for metadata types.
 
Drawbacks :
  • This raw approach to creating the channel factory and channel may not be perceived as friendly as the generated proxy.
You don t have access to channel properties such as SessionId (from IContextChannel) or Open and Close methods (from ICommunicationObject) without casting explicitly to those interfaces first.


 Example :

InterFace :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WC_MetaDataMethod
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string SimpleMethod(string msg);
    }
}


Service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WC_MetaDataMethod
{
    public class Service1 : IService1
    {
        public string SimpleMethod(string msg)
        {
            return "Hello " + msg;
        }
    }

}


WebConfig :
<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="false" />
    <behaviors>
     
     
      <serviceBehaviors>
        <behavior name="SimpleServiceBehavior">        
          <serviceMetadata httpGetEnabled="true"  policyVersion="Policy15"/>     
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
     
     
    </behaviors>


    <services>
      <service name="WC_MetaDataMethod.Service1" behaviorConfiguration="SimpleServiceBehavior">
   <endpoint name="" address="http://localhost:56653/Service1.svc" binding="wsHttpBinding"          contract="WC_MetaDataMethod.IService1"/>

        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>


Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using WC_MetaDataMethod;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {

            WSHttpBinding myBinding = new WSHttpBinding();
            EndpointAddress myEndpoint = new EndpointAddress("http://localhost:56653/Service1.svc");
ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>(myBinding, myEndpoint);
            
            myChannelFactory.Open(); 
            IService1 instance = myChannelFactory.CreateChannel();
            // Call Service.
            Console.WriteLine(instance.SimpleMethod("My Dear"));
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
            myChannelFactory.Close();



        }
    }
}



OutPut :

Hello My dear,
Press enter to exit





Proxy 

 
·         The proxy is a CLR class that exposes a single CLR interface representing the service contract.
·         The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service.
·         The proxy completely encapsulates every aspect of the service:   location, implementation technology and runtime platform, and the communication transport.
·         The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference and By using SvcUtil.exe
   The proxy generated from both ways by default several things are created from proxy generation:

1.       configuration file with settings to invoke each service endpoint,
2.       proxy wrapper class that encapsulates calls to each service operation
3.       copy of the service contract
4.       Copy of all data contracts, message contracts, and fault contracts necessary to support calls to and from service operations.




Benefits of generating proxies using SvcUtil include:
  • All the necessary metadata required to communicate with the service is generated for you.
  • Data contracts implement IExtensibleDataObject for version tolerance and INotifyPropertyChanged to support client-side data binding.
  • The proxy provides access to other underlying channel properties, such as SessionId and Open and Close methods.
  • Endpoint configuration necessary to initialize the proxy is automatically generated.
  




Difference between Proxy and chanel factory

Proxy
Channel Factory
Only requires a URL where the service resides
You must have direct access to the assembly that contains the service contract
Very simple
Not easier
Easy to understand
Channels are complex, network-related
Visual Studio gives you the Add the Reference option
When you share a common service contract DLL between the client and the server, you'll be using the ChannelFactory class
Proxies have several restrictions like:
  1. Properties need to have gets and sets
  2. Constructors can't be exposed
  3. Methods other than the service contract cannot be exposed
If you know that your entities will not change much and the client code is less, then a DLL would work better than a proxy
By using SVCutil.exe, you can create a proxy
When you are using a DLL that refers to the service contract interface then use the channel factory class
 













1 comment :