Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IUrlHelper not being resolved in RC2

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?

like image 593
kdaveid Avatar asked May 19 '16 09:05

kdaveid


1 Answers

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

like image 193
kdaveid Avatar answered Oct 14 '22 12:10

kdaveid