tags:

views:

542

answers:

1

I'd like to centralize creation of my WCF proxies in a WPF client application. During creation of each proxy I'd like to define programaticaly specific endpoint behaviors (adding localization headers etc) and define client credential settings (I'm using message level security with UserName client credentials). The creation of proxy should look like this:

public class ServiceChannelFactory
{
 public T CreateChannel<T, TService>() where T : ClientBase<TService>
 {
  var proxy = new T(bindingBuilder.GetBinding(), endpointBuilder.GetEndpointAddress()); //!!!
  proxy.Endpoint.Behaviors.Add(new LocalizationEndpointBehavior());
  proxy.ClientCredentials.UserName.UserName = applicationContext;
  proxy.ClientCredentials.UserName.Password = txtPassword.Password;
  return proxy;
 }
}

and usage should look like this:

var scp = new ServiceChannelFactory();
var proxy = scp.CreateChannel<MyServiceClient, ICustomerService>();
proxy.Open();
try
{
    proxy.CallService();
}
finally
{
    proxy.Close();
}

but I'm not able to figure out how to actually create the the proxy object without using reflection (the //!!! commented line).

MyServiceClient class is generated by VS>Add Service Reference.

Is there any best-practices solution to this problem?

+1  A: 

If you add a new() constraint, you can create an instance of the generic type, assuming it has a paramaterless constructor.

public class ServiceChannelFactory 
{ 
    public T CreateChannel<T, TService>() where T : ClientBase<TService>, new()
    { 
        var proxy = new T();

        //Configure proxy here

        return proxy; 
    } 
}
Bryan Batchelder
you're right - I thought Endpoint.Binding and Address have no setters so I didn't realize it's just so easy :) thanks
Buthrakaur