Note that there are some explanatory texts on larger screens.

plurals
  1. POC#: Elegant way to wrap method calls
    primarykey
    data
    text
    <p>Apologies for the fairly ambiguous title but what I'm trying to achieve is probably better stated in code.</p> <p>I have a WCF client. When I'm calling methods I would like to wrap each call in some error handling code. So, instead of exposing the methods directly, I've created the following helper function on the client class:</p> <pre><code> public T HandleServiceCall&lt;T&gt;(Func&lt;IApplicationService, T&gt; serviceMethod) { try { return serviceMethod(decorator); } [...] } </code></pre> <p>And the client code uses it like this:</p> <pre><code>service.HandleServiceCall(channel =&gt; channel.Ping("Hello")); </code></pre> <p>And the call to Ping gets nicely wrapped in some logic that will try to handle any errors.</p> <p>This works great except that I now have a requirement to know which methods are actually being called on the service. Initially , I was hoping to just inspect the <code>Func&lt;IApplicationService, T&gt;</code> using Expression trees but didn't get very far.</p> <p>Finally, I settled on a Decorator pattern:</p> <pre><code> public T HandleServiceCall&lt;T&gt;(Func&lt;IApplicationService, T&gt; serviceMethod) { var decorator = new ServiceCallDecorator(client.ServiceChannel); try { return serviceMethod(decorator); } [...] finally { if (decorator.PingWasCalled) { Console.Writeline("I know that Ping was called") } } } </code></pre> <p>And the Decorator itself:</p> <pre><code> private class ServiceCallDecorator : IApplicationService { private readonly IApplicationService service; public ServiceCallDecorator(IApplicationService service) { this.service = service; this.PingWasCalled = new Nullable&lt;bool&gt;(); } public bool? PingWasCalled { get; private set; } public ServiceResponse&lt;bool&gt; Ping(string message) { PingWasCalled = true; return service.Ping(message); } } </code></pre> <p>It's really clunky and quite a lot of code. <em>Is there a more elegant way of doing this?</em></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload