Adding a Closing EventHandler in WCF makes Username Read Only

Ok, here’s another weird experience, I’ve been building a static class to cache my WCF Service Clients so that they could be used efficiently in ASP.NET. It’s basically contains Dictionary<TKey, TValue> of Services against a list of service types. This was all working perfectly, but I thought I’d add some logic to remove references to any services that were not closed by my cache class. To do this I added a ICommunicationObject.Closing event handler to my cache when I created a new instance of the service.

Example

private static T CreateService<T>() where T : class, ICommunicationObject, new()
{
    List<ICommunicationObject> list = null;
    lock (clientsSyncRoot)
    {
        if (ServiceClients.ContainsKey(typeof(T)))
        {
            list = ServiceClients[typeof(T)];
        }
        else
        {
            list = new List<ICommunicationObject>();
            ServiceClients.Add(typeof(T), list);
        }
    }
    T obj = new T();
    obj.Closing += new EventHandler(Service_Closing);
    list.Add(obj);
    return obj;
}

private static void Service_Closing(object sender, EventArgs e)
{
    ICommunicationObject serviceClient = sender as ICommunicationObject;
    if (serviceClient == null)
        return;
    lock (clientsSyncRoot)
    {
        if (OpenClients.Contains(serviceClient))
        {
            OpenClients.Remove(serviceClient);
        }
    }
}

This had the oddest behaviour of locking my service client’s .ClientCredentials.UserName property, marking it read-only and threw an exception ‘Object is Read Only’, ensuring I could never set the credentials for my Service. I still have not figured out why this happens, but removing the Closing event handler fixed it again… I give up…

Advertisements
  1. #1 by richard.lowe on May 29, 2008 - 2:19 am

    I got this error when I tried to assign the UserName property of the UserName ClientCredentials *twice* on a single cached ServiceClient.   It seems that once you provide credentials, you cannot change them.  Simply checking if the UserName was already provided solved this error for me.   I\’m not sure if or why you were able to ever really set the credentials more than once on a service client, if you were, it would be interesting to know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: