If I were to make a site with a mutable language like C# and use NHibernate, I would normally approach sessions with the idea of making them as create only when needed and dispose at request end. This has helped with keeping a session for multiple transactions by a user but keep it from staying open too long where the state might be corrupted.

In an immutable system, like F#, I would think I shouldn't do this because it supposes that a single session could be updated constantly by any number of inserts/updates/deletes/ect... I'm not against the "using" solution since I would think that connecting pooling will help cut down on the cost of connecting every time, but I don't know if all database systems do connection pooling. It just seems like there should be a better way that doesn't compromise the immutability goal.

Should I just do a simple "using" block per transaction or is there a better pattern for this?

2 Answers 2


I'm kind of taking a wild guess here since I'm absolutely unfamiliar with F#, but it sounds like our talking about a context manager type structure similiar to the one outlined in this article:

/// <summary>
/// Returns a shared ObjectContext instance.
/// </summary>
public NorthwindObjectContext ObjectContext
        string ocKey = "ocm_" + HttpContext.Current.GetHashCode().ToString("x");
        if (!HttpContext.Current.Items.Contains(ocKey))
            HttpContext.Current.Items.Add(ocKey, new NorthwindObjectContext());
        return HttpContext.Current.Items[ocKey] as NorthwindObjectContext;

Complete Article here:


In the past I've used a "one context per request" idea and love it.. the "using" method is just too small of a scope for me.


To be language agnostic the issue you are talking about is binding a connection/transaction to some "context" and then doing some very stateful and procedural communication to the connection and then disposing/closing/committing the connection/transaction and then finally removing the connection/transaction from the "context".

Worse in most languages this "context" is maintained in a ThreadLocal which is sort of equivalent to a global variable.

My guess is F# probably does what C# does but if you did want to do this in a more FP way I would look at implementing it as a Monad and see how Haskell manages database stuff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.