Thursday, August 7, 2008

WCF Client Proxy IDisposable - Generic WCF Service Proxy

I have run into this issue on several clients now.  The basic issue is when using WCF on the client, using ClientBase<>, and you do not close the channel, you can tie up the server until the channel times out.  So, once the max instances, sessions, or concurrent calls is reached and the clients are not closing their channels, the server will block and queue up subsequent calls.  The un-closed client channels will eventually timeout, which causes a fault on the client, and the next set of calls will then make it through.

When I first hit this issue, my thought was to wrap my client base code in a using () statement so Dispose() would then be called.  But, ClientBase<> does not implement IDisposable.  Here is some info on the issue...

Guidance on factory close and message faults

Why does ClientBase Dispose need to throw on faulted state

So, after lots of testing to understand all the WCF knobs to tweak, I came up with a generic class I called ServiceProxy for clients to use when creating/using client channels.  This has been through several revisions and here is what I have ended up with.  The idea to add support for the delegate came from this blog entry

iServiceOriented.com

Here is the code for my generic service proxy wrapper...

public class ServiceProxy<TInterface> : ClientBase<TInterface>, IDisposable where TInterface : class

    {

        public delegate void ServiceProxyDelegate<T>(TInterface proxy);

 

        public ServiceProxy()

            : base(typeof(TInterface).ToString())

        {

        }

        public ServiceProxy(string endpointConfigurationName)

            : base(endpointConfigurationName)

        {

        }

 

        protected override TInterface CreateChannel()

        {

            return base.CreateChannel();

        }

 

        public TInterface Proxy

        {

            get

            {

                return this.Channel;

            }

        }

 

        public static void Call(ServiceProxyDelegate<TInterface> proxyDelegate)

        {

            Call(proxyDelegate, typeof(TInterface).ToString());

        }

 

        public static void Call(ServiceProxyDelegate<TInterface> proxyDelegate, string endpointConfigurationName)

        {

            ChannelFactory<TInterface> channel = new ChannelFactory<TInterface>(endpointConfigurationName);

 

            try

            {

                proxyDelegate(channel.CreateChannel());

            }

            finally

            {

                if (channel.State == CommunicationState.Faulted)

                {

                    channel.Abort();

                }

                else

                {

                    try

                    {

                        channel.Close();

                    }

                    catch

                    {

                        channel.Abort();

                    }

                }

            }

        }

 

        public void Dispose()

        {

            if (this.State == CommunicationState.Faulted)

            {

                base.Abort();

            }

            else

            {

                try

                {

                    base.Close();

                }

                catch

                {

                    base.Abort();

                }

            }

        }

    }

 

And, here are some usages samples...

//delegate example1

            string response = null;

            ServiceModel.ServiceProxy<IUnitTestService>.Call(p =>

            {

                response = p.DoStuff("ServiceProxyUsingTest");

            }

            );

 

            //delegate example2

            string response = null;

            ServiceProxy<IUnitTestService>.Call(p => response = p.DoStuff("ServiceProxyUsingTest"));

 

            //using example

            string response = null;

            using (ServiceProxy<IUnitTestService> service = new ServiceProxy<IUnitTestService>())

            {

                response = service.Proxy.DoStuff("ServiceProxyUsingTest");

            }

15 Comments:

Blogger Julian Maughan said...

Nicely done. Thanks.

January 27, 2009 at 6:54 PM  
Anonymous Anonymous said...

I loved your post on this. I made some small changes to fit our needs -- I gave you back credit in my post.

http://www.traviswhidden.com/PublicBlog/tabid/358/EntryId/415/Generic-WCF-Client.aspx

My changes were just to accept the URI instead of the endpointname, and the receive window (we have some big datasets that can be returned).

Thanks again for this great example. That was exactly what I wanted to do, without writing it for myself first ;)

June 16, 2009 at 7:13 PM  
Anonymous Anonymous said...

instructions for viagra use cheap viagra tablets watermelon viagra non prescription viagra which is better cialis or viagra women taking viagra buy viagra cheap viagra jelly viagra sample buying viagra online in britain viagra canada viagra over the counter buy viagra in london england viagra suppliers

November 10, 2009 at 5:45 PM  
Anonymous Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

November 17, 2009 at 8:33 AM  
Anonymous Anonymous said...

Hello
phentermine pills

Phentermine is yet another important medication drugs in the medicinal field.
[url=http://dreamsindia.com/]cheap phentermine online[/url]
Tone up your bodyOrder Phentermine meds at one of reliable online pharmacies. No prescription!
http://dreamsindia.com/ - cheap phentermine online
For this you need to follow a regular set dieting chart and you will observe the change within few days.

November 21, 2009 at 10:03 AM  
Anonymous Anonymous said...

Could not find a suitable section so I written here, how to become a moderator for your forum, that need for this?

November 23, 2009 at 5:17 AM  
Anonymous Anonymous said...

...please where can I buy a unicorn?

November 30, 2009 at 1:22 AM  
Anonymous Anonymous said...

[url=http://italtubi.com/tag/Azione-di-Levitra/ ]acquisto levitra online [/url] zvPiuttosto che criticare meglio scrivere le loro opzioni. levitra fcbapzperp [url=http://www.mister-wong.es/user/COMPRARCIALIS/comprar-viagra/]comprar cialis[/url]

December 23, 2009 at 5:42 AM  
Anonymous Anonymous said...

fortres 101 crack
tweak xp pro 4 serial crack
always resume crack
serial no. crack
eprofiles crack




smartmovie crack keygen
advanced call recorder 1.5 crack
style xp male keygen
crack for virtual dj
query tool crack
dvdidle pro crack 5.65
impotrapide crack 2004
adobe photshop cs crack
cdxtract 4 crack
ulead media studio pro 8 crack
fl studio 5.01 crack
obscure game crack
microsoft windows xp service pack 2 crack
warez p2p spyware
polar golfer keygen
mechwarrior mercenaries crack
antamedia 5.0.12 crack
codesmart 2005 for vb6 crack
officefix 4 crack
need for speed most wanted no cd crack
codes crack
tutorial photo shop warez
microsoft validation crack

December 24, 2009 at 6:08 AM  
Anonymous Anonymous said...

Es ist schade, dass ich mich jetzt nicht aussprechen kann - es gibt keine freie Zeit. Aber ich werde befreit werden - unbedingt werde ich schreiben dass ich in dieser Frage denke. viagra generika schweiz viagra [url=http//t7-isis.org]levitra kaufen[/url]

December 31, 2009 at 2:29 AM  
Anonymous Anonymous said...

En lugar de criticar escriban mejor las variantes. http://nuevascarreras.com/category/cialis-generico/ cialis 20 mg wikipedia Frase meravigliosa e sul tempo [url=http://nuevascarreras.com/tag/cialis/ ]cialis 5 mg pvp [/url]

January 9, 2010 at 11:07 AM  
Anonymous Anonymous said...

mirando que carГЎcter del trabajo [url=http://csalamanca.com/ ]la viagra es mala [/url] su respuesta es incomparable...:) http://csalamanca.com/tag/comprar-viagra/ viagra es de venta libre

January 10, 2010 at 4:34 AM  
Anonymous Anonymous said...

Y probabais asГ­? http://nuevascarreras.com/tag/cialis-online/ comprar cialis contrareembolso Meravigliosa, molto utile idea [url=http://nuevascarreras.com/cialis/ ]cialis 20 [/url]

January 12, 2010 at 9:30 AM  
Blogger jackquil said...

Lots of great information on this site. I stumbled across your site on Google, and I’m glad that I did… I’ve bookmarked your site and will check back regularly. Keep the good content coming!


antioxidant supplements
best hgh products
buy hgh
genf20

June 29, 2010 at 12:10 AM  
Anonymous Anonymous said...

casino no deposit bonus codes, casino free chips
Welcome 카지노 to the world of online casino slots, no deposit bonus codes, casino leovegas free chips and casino free spins. 【2021】t-mobile no deposit bonus codes.

January 23, 2022 at 12:33 PM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home