Jez
Jez

Reputation: 30073

Is it possible to determine the ASP.NET Core hosting environment in an HTML helper method?

I'm writing an HTML helper method in ASP.NET Core and I want to detect the current hosting environment. The given way to do this is using DI, for example:

public class MyClass {
    private readonly IHostingEnvironment _hostingEnvironment;

    public MyClass(IHostingEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }

    public void Xyzzy() {
        var environment = _hostingEnvironment.EnvironmentName;
        [...]
    }
}

However HTML helper methods are extension methods and must therefore be static, so DI can't be used. I can't seem to see anything in the IHtmlHelper object that tells me the current hosting environment; how can I find it from my HTML helper method?

Upvotes: 3

Views: 639

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93213

IHtmlHelper has a ViewContext property, which itself has a HttpContext property. With this, you can use GetRequiredService to get hold of IHostingEnvironment. Here's an example:

htmlHelper.ViewContext.HttpContext.RequestServices
    .GetRequiredService<IHostingEnvironment>();

This isn't DI: it's using the Service Locator pattern, which is often called an antipattern. If you want to use DI, consider creating a Tag Helper instead of an IHtmlHelper extension method. That would also mitigate the need to nest all of those property access calls.

Upvotes: 4

Related Questions