.net - .NET Core 5.0 Singleton 访问 Configuration 和 HttpContext
问题描述
我有点迷路,正在寻求帮助。当我刚刚通过以下方式启动配置时,我有一个单例“工具”类可以正常工作:
public Tools(IConfiguration configuration)
{
Configuration = configuration;
Key = Configuration["NothingImportant"];
}
在 Startup.cs 中启动为
services.AddSingleton(new Tools(Configuration));
这工作正常。但是,我需要从使用 HttpContext.Current.User.Identity 的旧 .net 标准应用程序中添加一个方法。因此,看来我应该能够更改为:
public Tools(IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
{
Configuration = configuration;
Key = Configuration["NothingImportant"];
_httpContextAccessor = httpContextAccessor;
}
并能够访问访问器?但是,我无法弄清楚如何从启动中初始化它并同时拥有配置和 httpcontext?
解决方案
如果你想添加 HttpContextAccessor 你应该添加
services.AddHttpContextAccessor();
到你的Startup
班级,然后你应该能够使用IHttpContextAccessor
注入。
您可以使用服务提供者委托在启动配置中注入所需的服务:
services.AddSingleton(serviceProvider => new Tools(Configuration, serviceProvider.GetRequiredService<IHttpContextAccessor>()));
推荐阅读
- database - 如何在 Corda 社区版中使用数据源类型 DB 建立 rpc 属性?
- appium - 屏幕截图未通过侦听器类捕获
- node.js - Raspbian OS 中的 Firestore 快照失败
- python - 在共享文件夹中阅读 Outlook 电子邮件 - Python
- angular - 在页面加载时使用默认值设置下拉选择选项
- php - 是否可以在我的 php 代码中使用多卷曲?
- amazon-web-services - AWS - 通过 NAT 网关发送 Internet 流量和私有到另一个 VPC
- angular - Angular 服务从回调函数返回 observable
- reactjs - 如何在单个二进制文件中使用 ReactJS GUI 构建 Go 应用程序?
- ssis - 跨域访问共享文件夹时,SSIS 包无法使用 SQL 作业执行