While migrating from ASP.NET Core RC1 to RC2 my TagHelpers do not resolve the injected IUrlHelpers.
[HtmlTargetElement("usermenulink", Attributes = "controller-name, action-name, menu-text, menu-item, active-item")]
public class UserMenuItemTagHelper : TagHelper
{
public IUrlHelper _UrlHelper { get; set; }
public UserMenuItemTagHelper(IUrlHelper urlHelper)
{
_UrlHelper = urlHelper;
}
//... abbreviated
}
Instead I get an exception:
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' while attempting to activate '...TagHelpers.UserMenuItemTagHelper'.
Any ideas?
I found out myself that with RC2 you have to (or can) inject an IUrlHelperFactory and get an UrlHelper instance of this.
public class UserMenuLinkTagHelper : TagHelper
{
[ViewContext]
public ViewContext ViewContext { get; set; }
public IUrlHelperFactory _urlHelperFactory { get; set; }
public UserMenuLinkTagHelper(IUrlHelperFactory urlHelperFactory)
{
_urlHelperFactory = urlHelperFactory;
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext);
string menuUrl = urlHelper.Action(ActionName, ControllerName);
//...
}
}
Here is the example of the current implementation of the Mvc team: https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.TagHelpers/ImageTagHelper.cs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With