Question

Having a WCF service and a Consumer I'm not really sure how to handle the Open and Close methods and the lifetime of my Client.

I created the client myself extending and implementing ClientBase and IMyService. Let's call it MyServiceClient

One place I use it for example is MembershipProvider. So I gave MembershipProvider a MyClient as member variable.

I would like to have it instanced once in the MembershipProvider (via IoC container) and then perhaps do a Open and Close call inside every method call in the client.

    public bool ValidateUser(string username, string password)
    {
        this.Open();
        bool b = Channel.ValidateUser(username, password);
        this.Close();
        return b;
    }

Is this the right way to go about it. I don't really understand what's really happening when open/close is called and how having one instance of client affects the service (if at all).

Was it helpful?

Solution

One of the problems with using a single client (WCF proxy) instance is that when a fault occurs the proxy enters a faulted state, and it cannot be reused or Dispose-d, only Abort-ed and created anew. On the other hand, if you use/require Sessions on the service side you need the same proxy instance across multiple calls.

In any case, if you would like to use proxy now and worry about transport, sessions or faults later I suggest a wrapper like this that I use for my WCF proxies:

TResult ExecuteServiceMethod<TResult>(Func<MyService, TResult> method)
{
    var proxy = new MyService(); //...Or reuse an existing if not faulted
    try
    {        
        return method(proxy);
    }
    catch(Exception e)
    {
        //...Handle exceptions
    }
    finally
    {
        //...Per-call cleanup, for example proxy.Abort() if faulted...
    }
}

and you call your service methods like this:

var result = ExecuteServiceMethod((MyService s) => s.VerifyUser(username, password));

Replace MyService with your actual client type. This way you can later change your opening/closing/reusing strategy, add logging, etc. for all service calls by adding code before or after the line return method(client).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top