Posted by: Mark Wilkinson | July 8, 2009

Dynamic Connection String to WCF Host

Another issue I came across was needing a way to dynamically connect to a WCF host without using the app.config file (which in all examples I see, they put the connection string in the app.config).

In code you can specify the endpoint address like so, with the “localhost:8008″ being the tcp address you want:

InstanceContext instanceContext = new InstanceContext(this);
client = new Service1Client(instanceContext);

client.Endpoint.Address = new EndpointAddress(“net.tcp://localhost:8008/Service1″);

Posted by: Mark Wilkinson | July 8, 2009

First post

Something I’ve come across using WCF.

A co-worker said he was getting exceptions when a network connection was dropped, and his proxy client state would drop (thus throwing an exception).

My solution that I’ve been using when trying to invoke any WCF client method is to do the following, thus preventing an exception from occuring:

if (client != null && client.State == CommunicationState.Opened)
{
    client.Method();
}
else
    this.ConnectToWCFHost();

If it’s null, try reconnecting and instantiating the client instance.  You might want to count the number of attempts to connect and then notify the system (through an event viewer for instance) that the connection cannot be established.

Categories