GenericProxy<T> at your service

17 באפריל 2006

tags:
2 comments


As a client that wants to communicate with the service, there are several ways to do so:


1. Use ChannelFactory<T> and call the service:


ChannelFactory<IContract> cf = 
   
new ChannelFactory<IContract>("endpoint");
IContractchannel = cf.CreateChannel();
channel.DoOperation();


2. Using svcutil tool that generates a typed proxy for you.
3. Implement a typed proxy that inherits from ClientBase<T>.


Here is a code sample of a generic proxy. This proxy also inherits from ClientBase<T>, but allows you not to created a specific class for each service. Additionaly I extended the class by overriding the CreateChannel method, where i added the credentials for the call.


/// <summary>
/// Generic Proxy for service calls.
/// </summary>
/// <typeparam name="T">The service Contract</typeparam>
public class GenericProxy<T> : ClientBase<T> where T : class
{
   
public GenericProxy(string endpoint)
   
: base(endpoint)
   {
   
}


   /// <summary>
   /// When creating the channel, set the credentials
   /// </summary>
   /// <returns></returns>
   protected override T CreateChannel()
   {
      this.ChannelFactory.Credentials.UserName.UserName = "user";
      this.ChannelFactory.Credentials.UserName.Password = "123456";
      return base.CreateChannel();
   }


   /// <summary>
   /// Returns the transparent proxy for the service call
   /// </summary>
   public T Proxy
   {
      get
      {
         return this.InnerProxy;
      }
   }
}


Using this class, your client code should look similar to this:


using ( GenericProxy<IContract> service = 
      
new GenericProxy<IContract>("endpoint"))
{
   service.Proxy.DoOperation(
"Guy");
}


Enjoy!


Guy

Add comment
facebook linkedin twitter email

2 comments

  1. Kyle5 באוגוסט 2008 ב 17:01

    Hi Guy,

    Looking through your code, it seems like something has changed, and now the property you refer to as InnerProxy is now known as Channel. Is this correct?

    Very helpful post, BTW. I abhor code generation.

  2. Vijay14 באוקטובר 2011 ב 16:54

    thanks for post, really helpful,
    Vijay

Comments are closed.