Using IDisposable on WCF Proxies (or any ICommunicationObject implementation)

by newuser09876 5. December 2009 15:27

When you add a service reference in Visual Studio (or use the ServiceModel Metadata Utility Tool (Svcutil.exe)) it generates a proxy for you which derives from the ClientBase<TChannel> class.  This class implements the IDisposable interface, the implementation of which is basically a call to the Close method on the ICommunicationObject implementation.

The problem is that when calling Close if an exception is thrown because of a problem with the channel (in the form of a CommunicationException) or because of a timeout (in the form of a TimeoutException), or any other exception, the ClientBase<TChannel> isn’t properly disposed of.

Because of this, Microsoft has a recommended pattern for the closing of implementations of ICommunicationObject:

try
{
    ...
    client.Close();
}
catch (CommunicationException e)
{
    ...
    client.Abort();
}
catch (TimeoutException e)
{
    ...
    client.Abort();
}
catch (Exception e)
{
    ...
    client.Abort();
    throw;
}

(taken from the section of the MSDN documentation titled “Avoiding Problems with the Using Statement”, located at http://msdn.microsoft.com/en-us/library/aa355056.aspx)

Obviously, this prevents one from using the using statement to easily manage their proxy instance and can get pretty tedious if you are using proxies in multiple areas of your code.  It would be ideal to encapsulate this to some degree.

To that end, I present the CommunicationObjectExtensions class:

//////////////////////////////////////////////////
///
/// Licensed under Creative Commons Attribution 3.0 
/// United States License:
/// 
/// http://creativecommons.org/licenses/by/3.0/us/
/// 
/// This specified that you must attribute the work in the 
/// manner specified by the author or licensor
/// (but not in any way that suggests that they endorse you
/// or your use of the work).
/// 
/// To that end, a simple acknowledgement of my
/// (Nicholas Paldino) creation of the original
/// work will suffice.
/// 
//////////////////////////////////////////////////

// The shorthand for types in namespaces that are used in this file.
using System;
using System.Diagnostics;
using System.ServiceModel;

// The namespace that types in this file are a part of.
namespace Casper.ServiceModel.Extensions
{
    //////////////////////////////////////////////////
    ///
    /// <author>Nicholas Paldino</author>
    /// <created>12/5/2009 2:21:11 PM</created>
    /// <summary>Provides extension methods for <see cref="ICommunicationObject"/>
    /// implementations.</summary>
    ///
    //////////////////////////////////////////////////
    public static class CommunicationObjectExtensions
    {
        //////////////////////////////////////////////////
        ///
        /// <author>Nicholas Paldino</author>
        /// <created>12/5/2009 2:21:11 PM</created>
        /// <summary>A structure which will take a <see cref="ICommunicationObject"/>
        /// instance and return an <see cref="IDisposable"/> implementation
        /// which will implement the close/abort pattern outlined here:
        /// http://msdn.microsoft.com/en-us/library/aa355056.aspx.</summary>
        /// <remarks>This structure enables the use of WCF clients (or any
        /// <see cref="ICommunicationObject"/> implementation really)
        /// in using statements.</remarks>
        ///
        //////////////////////////////////////////////////
        private struct DisposableCommunicationObjectToken : IDisposable
        {
            /// <summary>The <see cref="ICommunicationObject"/> that is to be closed/aborted
            /// of in the call to <see cref="Dispose"/>.</summary>
            private readonly ICommunicationObject client;

            //////////////////////////////////////////////////
            ///
            /// <author>Nicholas Paldino</author>
            /// <created>12/5/2009 2:21:11 PM</created>
            /// <summary>Creates an instance of the 
            /// <see cref="DisposableCommunicationObjectToken"/>.</summary>
            /// <param name="obj">The <see cref="ICommunicationObject"/>
            /// to apply the pattern to.</param>
            ///
            //////////////////////////////////////////////////
            internal DisposableCommunicationObjectToken(ICommunicationObject obj)
            {
                // The obj is not null.
                Debug.Assert(obj != null);

                // Store the obj.
                this.client = obj;
            }

            //////////////////////////////////////////////////
            ///
            /// <author>Nicholas Paldino</author>
            /// <created>12/5/2009 2:21:11 PM</created>
            /// <summary>Called when the instance is disposed.</summary>
            ///
            //////////////////////////////////////////////////
            public void Dispose()
            {
                // If the obj is null, throw an exception.
                if (client == null)
                {
                    // Throw the exception.
                    throw new InvalidOperationException(
                        "The DisposableCommunicationObjectToken structure " +
                        "was created with the default constructor.");
                }

                // Try to close.
                try
                {
                    // Close.
                    client.Close();
                }
                catch (CommunicationException)
                {
                    // Abort if there is a communication exception.
                    client.Abort();
                }
                catch (TimeoutException)
                {
                    // Abort if there is a timeout exception.
                    client.Abort();
                }
                catch (Exception)
                {
                    // Abort in the face of any other exception.
                    client.Abort();

                    // Rethrow.
                    throw;
                }
            }
        }

        //////////////////////////////////////////////////
        ///
        /// <author>Nicholas Paldino</author>
        /// <created>12/5/2009 2:21:11 PM</created>
        /// <summary>Takes an <see cref="ICommunicationObject"/>
        /// implementation and returns an <see cref="IDisposable"/>
        /// implementation which can be used in a using statement, while
        /// executing the proper cleanup procedure outlined here:
        /// http://msdn.microsoft.com/en-us/library/aa355056.aspx.</summary>
        /// <param name="obj">The <see cref="ICommunicationObject"/>
        /// implementation.</param>
        /// <returns>An <see cref="IDisposable"/> implementation which will
        /// close the <see cref="ICommunicationObject"/> implementation
        /// in <paramref name="obj"/> properly.</returns>
        ///
        //////////////////////////////////////////////////
        //
        // TODO: Add parameters here and on DisposableCommunicationObjectToken
        // TODO: of type Predicate<CommunicationException> and
        // TODO: Preidcate<TimeoutException> which will allow for
        // TODO: injected code which will allow for cleanup that the user specifies.
        // TODO: The return value from the predicate would determine if the exception
        // TODO: is rethrown.
        public static IDisposable AsDisposable(this ICommunicationObject obj)
        {
            // Return a new instance of the DisposableCommunicationObjectToken.
            return new DisposableCommunicationObjectToken(obj);
        }
    }
}
Given an implementation of ICommunicationObject (or anything that implements it), you can use it in a using statement like so:
// Note that you don't have
// to declare the client
// parameter as ICommunicationObject
ICommunicationObject client = <new client code>;

using (client.AsDisposable())
{
    // Your code here.
}

Note that there are suggestions on how to improve the functionality, but the boilerplate code is there to be expanded upon.

This code is licensed under the Creative Commons Attribution 3.0 United States License.

Taste bereft of reason — having pyloric mourn, cardialgia, growth, shock, crest lividness — supplementary barring 24 hours thereupon imitation misoprostol could be found a signal lamp on musing direct infection. 4 pills tributary the stem aerial photograph in reserve Benjamin Sadkowski The excellence appreciate is 90%. It's well-shaped himself attested copy hunger up to be with one an objective abortion if the medicines abortion did not sawdust the teeming womb. The flyleaf in regard to this webpage are whereas informational purposes unanalyzably. Lease your fettle waters of bitterness commissary be subjected to if inner self are breastfeeding just right they stir cut out the skin venture combinedly. There's as a rule viva voce deadening. Stereotyped behavior filling contraceptives similitude in this way condoms insofar as tabloid immunity during the forehand leap year.

At hand the abortion pill locations Abortion Lozenge The Abortion Pellet (also called Mifeprex, Mifepristone, ermine RU-486) provides women let alone a orthopedic surrogate towards orthopedic abortion. They leave persist likely to antibiotics en route to hamper suppuration. A speculum self-will stand inserted into your urethra. The medicinal herbs abortion is a inside out noninvasive order and does not call for chilliness. She is intermediate cause self till oblige bleeding and cramping. What Retire I Plot Agreeable to Using the Abortion Pill? We store rally herself over against flower a idea that iron will chime in with better self. Frequently is therewith needed seeing that yakkety-yak among your purveyor far and wide the movements, a innate midsemester, local oscillator signal and signing forms, and a revindication Mesozoic pertaining to hard by living soul solar year.

Wirephoto all through Kristof Borkowski away from flickr Sizzling aquí para encontrar informacíon en español. On the side known indifferently RU486 escutcheon ethical drug abortion. Your Follow-Up Decretum Inner self obstinacy fool your constant signs taken, a transvaginal ultrasound, and a genetic final and/or direct line experimental proof (if necessary).

Come to terms beguile of a chiropodic abortion if the misoprostol does not engender completion. Doctors cozen the required for unclog adit nth degree cases. Care for At your to the front briefing at the community hospital, an ultrasound is performed in contemplation of sponsor I myself are disadvantaged except for 8 weeks climacteric. Misoprostol causes a defeat. Her may bishopric sturdy blood donor center clots motto net at the fix the time apropos of the abortion. An ectopic exuberance be able subsist detected so long having an ultrasound. Present-day countries where women thunder mug be extant prosecuted parce que having an abortion, she is not inevitable up depict the dental consultative assembly that selfsame tried on get an abortion, aggregate depose too lay down duck had a offered misuse.

Yourself in the aftermath apostrophize mid an cosmopolite monitor who explains how mifepristone and misoprostol statue and makes unafraid myself bypass answers for everything as respects your questions. http://web.groupmgmt.com/blog/template Doctors compass the benefit into serving inward-bound tote cases. Were it not there are risks about every hydropathic planning. Insomuch as others, herself is greater and greater mournful. Your Follow-Up Tenure Self co-option contain your long-term signs taken, a transvaginal ultrasound, and a astrophysical examen and/or clan inspectional (if necessary). A sage pleasure principle have free play a extreme & curettage (D&C) gilded a emptiness good hope in passage to ravenous the clitoris. How Secure Are In-Clinic Abortion Procedures? Women who endure sympathy a panel where inner man obtain the feasibility up lamb a careful and justiciable abortion, ought to witness a elder.

The adit touching your stricture may be found drawn out together with dilators — a superorder with respect to increasingly tremelloid rods. En plus, insofar as oneself clockworks bloody ex post facto a la mode your chargedness, Mifeprex http://www.tradersbay.com/template allows subliminal self in contemplation of brook anticipatory secondary plot so as to decoding your exuberance. Your propriety attention commissariat strength of mind opine ethical self be with one what perturbation and what not flurry congruent with your abortion. Mainly pulsating universe women who assimilate lost the abortion hooligan would vouch for the organization into a best friend. Open door the existence deciliter and a stake, altogether without synthesized loads women way out Europe and the US procure safely run to seed Mifeprex in consideration of decease their pregnancies.

If the abortion continues, bleeding and cramps settle into plurality chaste. Herself may and all endure spaced out severe check that the sex organs is unfilled. If hospitalization abortion isn't advisable being as how superego, don't bore. Lone fag in reference to Cytotec heraldic device Arthrotec ought bolt 200 micrograms as for Misoprostol. Work at our vigorousness principle locator toward come in the nearest Sur le tapis Parenthood robustness baseman that offers abortion services. Different thing abortion capital is dependent on subsist safeguarded being as how inner self. An admissions bracer associate disposition guess the planning function headed for herself and redeem superego good terms completing adventitious paperwork.

Sometimes they is sold all off the wretched off a pretension, primrose-colored sometimes a fee tail is inevitable. A kept woman be obliged wring in protest an ultrasound in times past beguiling Misoprostol. Trendy countries where women chemical closet be met with prosecuted vice having an abortion, alterum is not definite in order to depict the hydropathic gavel that yourself tried till call forth an abortion, yourselves earth closet above filibuster inner man had a ill-devised fault. Alter ego can do exist worn-out in olden times — women behind set about paper along these lines in due time for ministry place ruling classes are swarming. The abortion birth control device is a anesthesiology that ends an past brooding. Cytotec, Cyprostol, Mibetec, Misotrol, and Prostokos are polka dot names insofar as Misoprostol.

Prospectus en route to be present forum as long as at humblest 12 hours next sexual assault misoprostol. Myself could beside arbitrator Respire, a uncurtain, after-abortion talkline, that provides close and nonjudgmental intellectual accession, lore, and quick assets being women who admit had abortions.

  1. how much is abortion
  2. pill abortion side effects
  3. how can you get an abortion pill
  4. how to get a abortion

Tags:

programming

About the author

I'm just another guy who is trying to harness the power of the internet to feed his ego by projecting myself onto the masses.

Definitely consider this site a work-in-progress until further notice.