Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5999263
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T00:31:40+00:00 2026-05-23T00:31:40+00:00

I’ve just started using Dapper for a project, having mostly used ORMs like NHibernate

  • 0

I’ve just started using Dapper for a project, having mostly used ORMs like NHibernate and EF for the past few years.

Typically in our web applications we implement session per request, beginning a transaction at the start of the request and committing it at the end.

Should we do something similar when working directly with SqlConnection / System.Transactions?

How does StackOverflow do it?

Solution

Taking the advice of both @gbn and @Sam Safron I’m not using transactions. In my case I’m only doing read queries so it seems there is no real requirement to use transactions (contrary to what I’ve been told about implicit transactions).

I create a lightweight session interface so that I can use a connection per request. This is quite beneficial to me as with Dapper I often need to create a few different queries to build up an object and would rather share the same connection.

The work of scoping the connection per request and disposing it is done by my IoC container (StructureMap):

public interface ISession : IDisposable {
    IDbConnection Connection { get; }
}

public class DbSession : ISession {

    private static readonly object @lock = new object();
    private readonly ILogger logger;
    private readonly string connectionString;
    private IDbConnection cn;

    public DbSession(string connectionString, ILogger logger) {
        this.connectionString = connectionString;
        this.logger = logger;
    }

    public IDbConnection Connection { get { return GetConnection(); } }

    private IDbConnection GetConnection() {
        if (cn == null) {
            lock (@lock) {
                if (cn == null) {
                    logger.Debug("Creating Connection");
                    cn = new SqlConnection(connectionString);
                    cn.Open();
                    logger.Debug("Opened Connection");
                }
            }
        }

        return cn;
    }

    public void Dispose() {
        if (cn != null) {
            logger.Debug("Disposing connection (current state '{0}')", cn.State);
            cn.Dispose();
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T00:31:41+00:00Added an answer on May 23, 2026 at 12:31 am

    This is what we do:

    We define a static called DB on an object called Current

    public static DBContext DB
    {
        var result = GetContextItem<T>(itemKey);
    
        if (result == null)
        {
            result = InstantiateDB();
            SetContextItem(itemKey, result);
        }
    
        return result;
    }
    
    public static T GetContextItem<T>(string itemKey, bool strict = true)
    {
    
    #if DEBUG // HttpContext is null for unit test calls, which are only done in DEBUG
        if (Context == null)
        {
            var result = CallContext.GetData(itemKey);
            return result != null ? (T)result : default(T);
        }
        else
        {
    #endif
            var ctx = HttpContext.Current;
            if (ctx == null)
            {
                if (strict) throw new InvalidOperationException("GetContextItem without a context");
                return default(T);
            }
            else
            {
                var result = ctx.Items[itemKey];
                return result != null ? (T)result : default(T);
            }
    #if DEBUG
        }
    #endif
    }
    
    public static void SetContextItem(string itemKey, object item)
    {
    #if DEBUG // HttpContext is null for unit test calls, which are only done in DEBUG
        if (Context == null)
        {
            CallContext.SetData(itemKey, item);
        }
        else
        {
    #endif
            HttpContext.Current.Items[itemKey] = item;
    
    #if DEBUG
        }
    #endif
    }
    

    In our case InstantiateDB returns an L2S context, however in your case it could be an open SQLConnection or whatever.

    On our application object we ensure that our connection is closed at the end of the request.

       protected void Application_EndRequest(object sender, EventArgs e)
       {
            Current.DisposeDB(); // closes connection, clears context 
       }
    

    Then anywhere in your code where you need access to the db you simple call Current.DB and stuff automatically works. This is also unit test friendly due to all the #if DEBUG stuff.


    We do not start any transactions per session, if we did and had updates at the beginning of our session, we would get serious locking issues, as the locks would not be released till the end.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I've got a string that has curly quotes in it. I'd like to replace
For some reason, after submitting a string like this Jack’s Spindle from a text
I want use html5's new tag to play a wav file (currently only supported
I have a JSP page retrieving data and when single or double quotes are
I'm looking for suggestions for debugging... If you view this site in Firefox or
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.