简体   繁体   中英

.NET Core 5.0 Singleton access to Configuration and HttpContext

I am little lost and looking for some help. I have a singleton "Tools" class that works fine when I was just starting up with the Configuration via:

        public Tools(IConfiguration configuration) 
    {
        Configuration = configuration;
        Key = Configuration["NothingImportant"];            
    }

Which is started in the Startup.cs as

services.AddSingleton(new Tools(Configuration));

This works fine. However, I needed to add a method from a older .net standard app that used HttpContext.Current.User.Identity. So, it appears I should be able to change to:

        public Tools(IConfiguration configuration, IHttpContextAccessor httpContextAccessor) 
    {
        Configuration = configuration;
        Key = Configuration["NothingImportant"];
        _httpContextAccessor = httpContextAccessor;
    }

and be able to access the accessor? However, I cannot figure out how to initialize this from startup and have both the configuration and the httpcontext?

If you want to add HttpContextAccessor you should add

services.AddHttpContextAccessor();

to your Startup class, and and then you should be able to use IHttpContextAccessor injection.

And you can use service provider delegate to inject required service in the startup configuration:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM