Home  /  Questions  /  Question



M S
50   50
Mar 22, 2010


Patterns In Action Model() lambda

I'm walking through Patterns In Action and the Model constructor has:

SafeProxy.DoAction<ActionServiceClient>(Service, client =>
                { response = client.GetToken(request); });

I looked up statement lambdas but am still confused how the above code works.

Can someone help explain?



555   99.9
Aug 17, 2010

Usually, I wouldn't reply to a question asked months ago. However, other people might stumble across this one and also wonder how this works (even tough this code is obsolete, Pattern Framework 4.0 has a slightly different approach). ;)

To understand how Lambda Expressions work, please read this article here:
http://msdn.microsoft.com/en-us/library/bb397687.aspx

And now... well,... I was about explaining how this code works and noticed that I don't understand it either. Lamdas tend to be not that intuitive to understand.

Service is a property that exposes a private field of type ActionServiceClient, while response is a local variable of type TokenResponse. request is a local instance of TokenRequest and initialized before the above call.

The static DoAction method has the following header:
public static void DoAction<T>(T client, Action<T> action) where T : ICommunicationObject

It does call action(client)

You need to know that the Lambda Expression here ressembles an anonymous method implementing an Action Delegate (Encapsulates a method that has no parameters and does not return a value). So in this case it is actually a typed action (hence the generic <T> which has a constraint that ensures that it implements the ICommunicationObject interface.

Alright... putting it all together:
The anonymous method "response = client.GetToken(request)" is called with client being actually the Service property that exposes an ActionServiceClient.

This happens from within the SafeProxy class that is supposed to be able to execute even long running actions (since the communication takes place over some sort of network using most probably WCF as a communication channel). The response is stored in the response object.

Hm... in the end I was somewhat able to explain a little bit...

To learn more about action delegates, please read the article here:
http://msdn.microsoft.com/de-de/library/system.action.aspx

And more than that: Go and get Pattern Framework 4.0.
The implementation of the models' c'tor looks way cleaner. ;-)

-Chris

 1 comment
 
Thanks Chris, Better late than never. I appreciate your response... --- M S  Aug 17, 2010