Skip to content

Instantly share code, notes, and snippets.

@dmitry-a-morozov
Last active April 5, 2016 00:29
Show Gist options
  • Save dmitry-a-morozov/d34761c19e88e7c9a867c1da5a531849 to your computer and use it in GitHub Desktop.
Save dmitry-a-morozov/d34761c19e88e7c9a867c1da5a531849 to your computer and use it in GitHub Desktop.
Scoped Action view via IDisposable object expression
open System
open System.Data
open System.Data.SqlClient
type SqlConnection with
//1. Open/close connection if it was not opened
//2. address an issue when regular Dispose on SqlConnection wipes out all properties like ConnectionString in addition to closing connection to db
member this.UseLocally() =
if this.State = ConnectionState.Closed
then
this.Open()
{ new IDisposable with member __.Dispose() = this.Close() }
else
{ new IDisposable with member __.Dispose() = () }
//opens connection on demand
let getTheAnswer(conn: SqlConnection) =
//scoped action
use __ =
if conn.State = ConnectionState.Closed
then
conn.Open()
{ new IDisposable with member __.Dispose() = conn.Close() }
else
{ new IDisposable with member __.Dispose() = () }
//or can be invocation to reusable function
//use __ = conn.UseLocally()
use cmd = new SqlCommand("SELECT 42", conn)
cmd.ExecuteScalar() |> unbox<int>
let getNow(conn: SqlConnection) =
use cmd = new SqlCommand("SELECT SYSDATETIMEOFFSET()", conn)
cmd.ExecuteScalar() |> unbox<DateTimeOffset>
do
use conn = new SqlConnection("Server=.;Trusted_Connection=yes")
getTheAnswer conn |> printfn "The answer is: %i"
conn.Open()
getNow conn |> printfn "Now is: %O"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment