Get session service using IServiceProvider

♀尐吖头ヾ 提交于 2021-02-18 22:42:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/39552601/get-session-service-using-iserviceprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!