使用IServiceProvider获取会话服务 [英] Get session service using IServiceProvider
问题描述
我需要使用IServiceProvider在ASP.NET Core 1.0中的ConfigureService方法中访问会话变量.
I need to access session variable in ConfigureService method in ASP.NET Core 1.0 using IServiceProvider.
我有一个使用委托/lambda表达式初始化的服务,可以从任何地方返回值.在这种情况下,此lambda表达式参数应在调用后从会话返回值.
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.
这是示例代码:
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();
}
我的会话配置良好(我可以在控制器中获取/设置值).但是,我无法从IServiceProvider获取服务.我找不到应该为GetServices方法提供什么类型来获取将找到会话的服务.
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.
推荐答案
Microsoft.AspNetCore.Session.DistributedSession
实现 ISession
,但是 ISession
未在DI系统中注册,因此无法直接解决.
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
.
您需要将 IHttpContextAccessor
注册到
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
并解决此问题,然后访问它的 HttpContext.Session
属性.您必须进行注册,因为自从RC2起,默认情况下就不再默认注册 IHttpContextAccessor
,如本公告中所述
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.
这篇关于使用IServiceProvider获取会话服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!