Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get session service using IServiceProvider

I need to access session variable in ConfigureService method in ASP.NET Core 1.0 using IServiceProvider.

I have a service that is initialized with delegate/lambda expression that can return value from any place. In this context this lambda expression argument should return value from session once called.

Here is example code:

public void ConfigureServices(IServiceCollection services)
{

     services.AddTransient<IMyService>(serviceProvider =>
            {
                return new MyService(() => {
                        var session = serviceProvider.GetServices<Microsoft.AspNetCore.Session.DistributedSession>().First();
                        return session.GetString("CompanyID");
                    }
                );
            }

      );

      // Add framework services.
      services.AddMvc();
      services.AddDistributedMemoryCache();
      services.AddSession();
}

My session is configured fine (I can get/set values in controllers). However, I cannot fetch the service from IServiceProvider. I cannot find what type should be provided to GetServices method to get a service that will find session.

like image 482
Jovan MSFT Avatar asked Sep 17 '16 23:09

Jovan MSFT


1 Answers

Microsoft.AspNetCore.Session.DistributedSession implements ISession, but ISession isn't registered with the DI system so you can't resolve it directly.

But as you can see here, the ISession is created during the execution of the Session middleware and put into the list of features (a list where a middleware can put data that can be consumed later on during the request). The HttpContext.Session property is populated from the ISessionFeature set during the session middleware call. So you can access it from HttpContext.

You'll need to register the IHttpContextAccessor with

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

and resolve this, then access it's HttpContext.Session property. You have to do the registration, because the IHttpContextAccessor isn't registered by default anymore since RC2, as mentioned in this announcement here on the GitHub issue tracker.

like image 119
Tseng Avatar answered Oct 19 '22 22:10

Tseng