在ASP.NET Core中注入IUrlHelper [英] Injection of IUrlHelper in ASP.NET Core
问题描述
在 RC1 中,可以将IUrlHelper
注入服务中(在启动类中添加services.AddMvc()
)
In RC1, IUrlHelper
could be injected in services (with services.AddMvc()
in startup class)
这在 RC2 中不再起作用.有人知道如何在 RC2 中做到这一点,因为刚刚更新UrlHelper
时需要一个ActionContext
对象.不知道如何在控制器之外获取该信息.
This doesn't work anymore in RC2. Does anybody know how to do it in RC2 as just newing up a UrlHelper
requires an ActionContext
object. Don't know how to get that outside a controller.
推荐答案
For ASP.NET Core RC2 there is an issue for this on the github repo. Instead of injecting the IUrlHelper
, take an IUrlHelperFactory
. It also sounds like you'd need the IActionContextAccessor
injected as a Controller
no longer has a public property ActionContext
.
注册依赖项:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
然后依靠它:
public SomeService(IUrlHelperFactory urlHelperFactory,
IActionContextAccessor actionContextAccessor)
{
var urlHelper =
urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
}
然后根据需要使用它.
这篇关于在ASP.NET Core中注入IUrlHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!