Mark
Mark

Reputation: 71

In ASP.NET core how do you inject a HttpContext into an extension method?

Porting an inherited ASP.NET application to ASP.NET core that used a SqlCommand extension method to implement a pseudo ambient transaction:

public static class SqlExtension
{
    public static SqlCommand NewCommand( this SqlConnection c )
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = c;

        SqlTransaction ambientTransaction = (SqlTransaction)
            HttpContext.Current.Items["AmbientTransaction"];

        if (ambientTransaction != null)
        {
            cmd.Transaction = ambientTransaction;
        }
        return cmd;
    }

Sql statements that use the ambient transaction are spread throughout the code in hundreds of places. Since HttpContext is no longer globally accessible, I'd appreciate suggestions:

1) On how get things working temporarily. Is it possible to inject the HttpContext into an extension method?

2) A pattern to follow as the code is re-implemented that accomplishes the same goal, namely wrapping a SQL transaction around all of the work done in a single http request.

Upvotes: 0

Views: 3307

Answers (3)

Julia Trikoz
Julia Trikoz

Reputation: 281

I found elegant solution in this article. First, you create static class AppContext, then configure it in Startup.cs in Configure method. Don't forget to add services.AddHttpContextAccessor(); in ConfigureServices method.

Upvotes: 0

Gabriel Castillo Prada
Gabriel Castillo Prada

Reputation: 4673

You have two options:

1.Resolve the dependency in the method directly, but I don't recommend it. Although you need as well the IApplicationBuilder

var httpContext =  (IHttpContextAccessor)app.ApplicationServices.GetService(typeof(IHttpContextAccessor))

2.Pass the parameter in the method

public static SqlCommand NewCommand( this SqlConnection c, IHttpContextAccesor http )
{
}

Upvotes: 1

Salman Farsi
Salman Farsi

Reputation: 5

Inject dependency on caller, just pass a parameter of HttpContext in extension method.

Upvotes: 0

Related Questions