Home Set a dto session key when calling WCF proxy
Post
Cancel

Set a dto session key when calling WCF proxy

The power of the following method is avoid implementing the WCF contract client in the client side and duplicate the code for each call. Using Reflections and Expression Lambda to handle each message before send it. The follwing code has 3 steps specified by regions :

  • Update the DTO.
  • Initilialize the proxy if the channel is in status Faulted.
  • Invoke the contract operation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public static Task<RequestResponse> SendRequestAsync(Expression<Func<IUiContract, Task<RequestResponse>>> expression)
        {
            #region Set Session Key

            var call = expression.Body as MethodCallExpression;
            if (call != null)
            {
                var argument = call.Arguments[0];
                if (argument != null)
                {
                    LambdaExpression lambda = Expression.Lambda(argument, expression.Parameters);
                    Delegate d = lambda.Compile();
                    var dto = d.DynamicInvoke(new object[1]) as RequestDTO;
                    if (dto != null)
                    {
                        dto.SessionKey = ClientSession.GetSessionKey();
                    }
                }
            }

            #endregion

            #region Initialize Proxy if Faulted

            // ReSharper disable once PossibleNullReferenceException
            if ((Instance._proxy as ICommunicationObject).State == CommunicationState.Faulted)
                Instance.InitializeProxy();

            #endregion

            var func = expression.Compile();
            return func.Invoke(Instance._proxy);
        }

Call the method from another class code:

1
  ServiceClient.SendRequestAsync(contract => contract.AddUserAsync(dto));
This post is licensed under CC BY-NC-SA 4.0 by the author.

Prism: View Model Locator => Custom Convention

How to connect to remote SSH Server without a password