Thursday, 4 February 2010

WCF Client Factory (Using Reflection & Generic Parameters) to set ClientCredentials

The following method (using reflection) works around the fact that the WCF generated proxies in .NET don't have a common non-generic interface. See code for a WCF proxy factory that sets basic client credentials (from a ConfigurationHelper class) and then returns the properly initialized client.

/// 
    /// Class for creating and initializing WCF proxy clients.
    /// 
    public class WCFClientFactory
    {
        /// 
        /// Gets an instance of WCF Proxy Class(Type "T"), and sets the credentials on it.
        /// 
        /// 
        /// /// 
        public static T CreateClient(CredentialType type)
        {
            object client = Activator.CreateInstance(typeof(T));
            ClientCredentials clientCredentials = 
                (ClientCredentials)client.GetType().GetProperty("ClientCredentials").GetValue(client, null);
            UserNamePasswordClientCredential credentials = clientCredentials.UserName;

            if (type == CredentialType.SAPBasic)
            {
                credentials.UserName = ConfigHelper.BackgroundUserName;
                credentials.Password = ConfigHelper.BackgroundUserPassword;
            }
            else if (type == CredentialType.MDM)
            {
                credentials.UserName = ConfigHelper.MDMUserName;
                credentials.Password = ConfigHelper.MDMPassword;
            }
        
            //Return initialized Proxy from Factory
            return (T)client;
        }

        //parameterless overload.
        public static T CreateClient()
        {
            return CreateClient(CredentialType.SAPBasic);
        }

You then call it like so:
Z_PO_CreateClient client = WCFClientFactory.CreateClient();

No comments: