Disposable Objects with Computation Expressions

The last post contains the description of a sqlMonad. It also happens to contain a silly and obvious (aren’t they all in hindsight) bug. The bug is in implementing the containing CmdSqlBuilder with the IDisposable.

While the intent was good (the class wraps resources that should be promptly disposed of – SqlCommand and SqlConnection):

        let connection = new SqlConnection(connectionString)
        let cmd = new SqlCommand(name, connection)

there is no real opportunity to use it in this way, since the underlying object is statically created in advance and so cannot be used as disposable objects normally are!

The fix is to clean thing up after each run like so:

        member this.Run( m : CmdSqlMonad<'a>) =
            try
                m cmd
            finally
                dispose()

Here, after each run, dispose() function should do its work closing connections and disposing of the command object. Disposable pattern should not be implemented as its application in this case makes no sense.

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.