IUrlHelper not being resolved in RC2
Asked Answered
L

1

9

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?

Lyra answered 19/5, 2016 at 9:17 Comment(0)
L
13

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

Lyra answered 19/5, 2016 at 10:2 Comment(4)
Thanks, it solves the issue, but did you find any reason why do we need to get factory instantiate this? Just seems a bit verbose.Norrisnorrv
The only reason I can think of is sharing the same instances of the UrlHelper around in one request. I have no other explanation.Lyra
Some additional info from asp.net Team: github.com/aspnet/Mvc/issues/3936#issuecomment-172104948Lyra
Do you see any problems by just registering it Scoped to the container? In my understanding Scoped is per Request. I am not sure if I correct understand the motivation behind the Asp.Net team.Nikianikita

© 2022 - 2024 — McMap. All rights reserved.