Connection on request

I am trying to maintain one connection per request in my web application.

The first time I try to connect to the database, every request I create a new instance of the connection and save it in HttpContext.Current.Items

, which works fine in a traditional web app, however it all falls apart when I use async await.

The problem is that it httpContact.Current

returns null when the async method is called (I assume this is because the current is associated with the original thread?).

Is there an alternative that will allow me to create and delete my connection for every request and still work while waiting for async?

Edit: sample code as requested

    public static DatabaseContext Context
    {
        get
        {
            if (HttpContext.Current.Items.Contains(DbContextKey))
            {
                return (DatabaseContext)HttpContext.Current.Items[DbContextKey];
            }

            var context = new DatabaseContext();
            HttpContext.Current.Items.Add(DbContextKey, context);
            return context;
        }
    }

      

+3


source to share


2 answers


To execute a thread HttpContext

through calls async-await

, you can set aspnet:UseTaskFriendlySynchronizationContext

in true

in your application config.

From MSDN :

When this key value is set to false [default], ASP.NET 4.5 asynchronous code paths behave the same as in ASP.NET 4.0. When this key value is set to true, ASP.NET 4.5 uses code paths that are optimized for APIs that return tasks. Setting this compatibility switch is required for WebSockets-enabled applications, for using task-based async in Web Forms pages, and for some other asynchronous actions. This will cause the ASP.NET application to use the new one AspNetSynchronizationContext

instead LegacyAspNetSynchronizationContext

:



<appSettings>
   <add  key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>

      

For more information, see What is the point of "UseTaskFriendlySynchronizationContext"? and Understanding SynchronizationContext in ASP.NET

+3


source


You can implement singleton pattern using ado.net

using System;
using System.Data;
using System.Data.SqlClient;
public class ConnSingleton{

    public static SqlConnection connInstance = null ;
    public static Object obj = new Object();

        public static SqlConnection GetInstance(string connstring)
            {
               if (connInstance == null)
                {
                     lock(obj){
                               if (connInstance == null)
                                  {
                                    connInstance = new SqlConnection (connstring);
                                   }
                               }
                 }
                return connInstance ;
            }

    }

      



Using

ConnSingleton.GetInstance("your connection string").Open();

      

-2


source







All Articles