November Happy Hour will be moved to Thursday December 5th.

Preferred way to access HttpContext in static classes

Vote:
 

I'm working my way through an Opti CMS 11 > 12 upgrade. I do not have my entire solution building yet but I have run into a few cases where I need to access the HttpContext in static instances.

First off, I have registered the IHttpContextAccessor in my services collection with the built in AddHttpContextAccessor() extension method.

Because of that, I'm thinking I can inject it like so:

private static Injected<IHttpContextAccessor> _httpContextAccessor;

However, I've read that I could also create a field and then initialize it like so in the constructor:

_httpContextAccessor = new HttpContextAccessor();

Are their any benefits/drawbacks to either approach? Like I said above, I don't have my upgrade running yet so apologies if one option doesn't even work.

#292402
Edited, Nov 29, 2022 22:27
Vote:
 

You should be using IHttpContextAccessor, so the former is preferred. The best way is still making your class not static if possible. 

#292437
Nov 30, 2022 7:18
Vote:
 

Thanks Quan

#292528
Dec 01, 2022 18:06
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.