首页 > 解决方案 > .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?

标签: .net.net-5

解决方案


如果你想添加 HttpContextAccessor 你应该添加

services.AddHttpContextAccessor();

到你的Startup班级,然后你应该能够使用IHttpContextAccessor注入。

您可以使用服务提供者委托在启动配置中注入所需的服务:

services.AddSingleton(serviceProvider => new Tools(Configuration, serviceProvider.GetRequiredService<IHttpContextAccessor>()));


推荐阅读