I have static helper class
public static class Current
{
public static string Host
{
get { return "httpContextAccessor here"; }
}
}
How I can get access to current HttpContext inside Host property?
I have static helper class
public static class Current
{
public static string Host
{
get { return "httpContextAccessor here"; }
}
}
How I can get access to current HttpContext inside Host property?
You can't and you shouldn't. This beats the whole purpose of having a dependency injection system at all. Static classes (for runtime data or Service Locator) is an anti-pattern.
In ASP.NET Core you have to inject
IHttpContextAccessor
in classes where you need it. You can make a non-static class and do something along the lines of:and in your class library inject it:
Be aware that your
SomeClassInClassLibrary
must be resolved with eitherScoped
orTransient
mode and it can't beSingleton
, becauseHttpContext
is only valid for the duration of the request.Alternatively if
SomeClassInClassLibrary
has to be singleton, you have to inject a factory and resolve theIRequestInformation
on demand (i.e. inside an action).Last but not least,
IHttpContextAccessor
isn't registered by default.Source: The IHttpContextAccessor service is not registered by default