WCF Service Client Lifetime

徘徊边缘 提交于 2019-11-29 02:08:54
marc_s

You're on the right track, I'd say ;-)

Basically, creating the WCF client proxy is a two-step process:

  • create the channel factory
  • from the channel factory, create the actual channel

Step #1 is quite "expensive" in terms of time and effort needed - so it's definitely a good idea to do that once and then cache the instance of ProjectWcfServiceFactory somewhere in your code.

Step #2 is actually pretty lightweight, and since a channel between a client and a service can fall into a "faulted state" when an exception happens on the server (and then needs to be re-created from scratch), caching the actual channel per se is less desirable.

So the commonly accepted best practice would be:

  • create the ChannelFactory<T> (in your case: ProjectWcfServiceFactory) once and cache it for as long as possible; do that heavy lifting only once

  • create the actual Channel (here: IProjectWcfService) as needed, before every call. That way, you don't have to worry about checking its state and recreating it as needed

UPDATE: "what about closing the channel?" asks Burt ;-) Good point!!

The acccepted best practice for this is to wrap your service call in a try....catch....finally block. The tricky part is: upon disposing of the channel, things can do wrong, too, so you could get an exception - that's why wrapping it in a using(....) block isn't sufficient.

So basically you have:

IProjectWcfService client = ChannelFactory.CreateChannel();
try
{
   client.MakeYourCall();
}
catch(CommunicationException ce)
{
    // do any exception handling of your own
}
finally
{
    ICommunicationObject comObj = ((ICommunicationObject)client);

    if(comObj.State == CommunicationState.Faulted)
    {
       comObj.Abort();
    }   
    else
    {
       comObj.Close();
    }
}

And of course, you could definitely nicely wrap this into a method or an extension method or something in order not to have to type this out every time you make a service call.

UPDATE:

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF http://ecx.images-amazon.com/images/I/41wYa%2BNiPML._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!