How to Access Session Data within a Hot Chocolate Resolver

Hot Chocolate is a GraphQL server that can integrate with ASP.NET Core, but it doesn’t participate in the same dependency injection you may be used to. That means it’s not immediately clear how to get at the Session or User objects.

Normally, you can access these things through an HttpContext.

  • On a controller, you read the HttpContext property.
  • In custom middleware, you add an HttpContext parameter to your Invoke method, and it is injected automatically.

Although Hot Chocolate has its own sort of dependency injection, none of these patterns applies when you need to access the HttpContext in a resolver. Making it work requires a few steps.

Start by updating the ConfigureServices method in your Startup class.

public void ConfigureServices(IServiceCollection services)
{
   services.AddHttpContextAccessor();

    // ...more service setup...
}

This causes ASP.NET to do some internal setup that allows IHttpContextAccessor to be injected into a class of your choosing, outside of the usual suspects (controllers, services, etc.).

Hot Chocolate will pass through this injection if you tag it with Hot Chocolate’s Service attribute:

public class MyResolver
{
    public SomeType GetSomeType([Service]IHttpContextAccessor httpContextAccessor)
    {
        var session = httpContextAccessor.HttpContext.Session;
        // Carry on...
    }
}

Alternatively, you could inject the IHttpContextAccessor into a lower-level component, then inject that component into your resolver. But although it’s nice to have that option available, it’s usually best to keep HttpContext out of business logic components.

References