ASP。NET 5 (vNext)环境标记助手代码

时间:2022-07-07 02:42:43

I'm trying to determine how to get the functionalty of this tag helper in any class file:

我正在尝试确定如何在任何类文件中获得这个标记助手的功能:

<environment names="Development"> </environment>

I understand that environment information is available via an IHostingEnvironment object, but I'm not sure how to grab it without dependency injection.

我知道环境信息是通过IHostingEnvironment对象提供的,但是我不知道如何在不依赖注入的情况下获取它。

Is it possible to get DI registered service implementations from any class?

是否可以从任何类获得DI注册的服务实现?

In this specific case, I'm writing some HtmlHelper extension methods, but I think the question applies in a broader sense.

在这个特定的例子中,我正在编写一些HtmlHelper扩展方法,但是我认为这个问题在更广泛的意义上是适用的。

1 个解决方案

#1


1  

So, from inside of an IHtmlHelper extension method, this works:

因此,从IHtmlHelper扩展方法的内部,它可以工作:

IHostingEnvironment env = HtmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment;

Is there a more generic way to grab a service instance without relying on dependency injection?

是否有更通用的方法来获取服务实例而不依赖依赖于依赖注入?

#1


1  

So, from inside of an IHtmlHelper extension method, this works:

因此,从IHtmlHelper扩展方法的内部,它可以工作:

IHostingEnvironment env = HtmlHelper.ViewContext.HttpContext.RequestServices.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment;

Is there a more generic way to grab a service instance without relying on dependency injection?

是否有更通用的方法来获取服务实例而不依赖依赖于依赖注入?