是否可以通过HTML帮助器方法确定ASP.NET Core托管环境?

问题描述 投票:0回答:1

我正在ASP.NET Core中编写HTML帮助器方法,并且我想检测当前的托管环境。给定的方法是使用DI,例如:

public class MyClass {
    private readonly IHostingEnvironment _hostingEnvironment;

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

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

但是HTML帮助器方法是扩展方法,因此必须是静态的,因此不能使用DI。我似乎看不到IHtmlHelper对象中的任何内容可以告诉我当前的托管环境。如何从我的HTML助手方法中找到它?

c# asp.net-core dependency-injection html-helper
1个回答
0
投票

IHtmlHelper具有ViewContext属性,其本身具有ViewContext属性。这样,您可以使用HttpContext来持有HttpContext

GetRequiredService

这不是DI:它使用的是Service Locator模式,通常称为GetRequiredService。如果要使用DI,请考虑创建IHostingEnvironment而不是htmlHelper.ViewContext.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>(); 扩展方法。

© www.soinside.com 2019 - 2024. All rights reserved.