12

I want to use IUrlHelper through dependency injection to be able to use its functionality to generate uris for different rest endpoints. I cant seem how to figure out how to create a UrlHelper from scratch because it changed in MVC 6 and MVC doesnt automatically have that service available in the IoC controller.

The setup is my Controller take in an internal model to api model converter class and that uses the IUrlHelper (all through Depenedency Injection).

If there is a better alternative to IUrlHelper/UrlHelper I can use to generate Uris for my WebApi action/controllers I am open to suggestion.

Gekctek
  • 1,161
  • 2
  • 12
  • 23
  • Is there an option you could wrapper the exiting UrlHelper, for example IUrlWrapper, then use the wrapper instead? – Spock Jun 26 '15 at 01:40
  • I would need the urlhelper still correct? How would that be different – Gekctek Jun 26 '15 at 02:05
  • Yes I can't think of a way you would not avoid a UrlHelper. From DI point of view, you need to create a wrapper as I mention before. – Spock Jun 26 '15 at 03:49
  • I guess im not understanding. How am I suppose to wrap the UrlHelper if I dont know how to get it. – Gekctek Jun 29 '15 at 21:46
  • Does this answer your question? [Injection of IUrlHelper in ASP.NET Core](https://stackoverflow.com/questions/37322076/injection-of-iurlhelper-in-asp-net-core) – Jeremy Frey Sep 22 '21 at 13:31

4 Answers4

14

The UrlHelper requires the current action context, and we can acquire that from the ActionContextAccessor. I'm using this:

        services.AddScoped<IActionContextAccessor, ActionContextAccessor>();
        services.AddScoped<IUrlHelper>(x =>
        {
            var  actionContext = x.GetService<IActionContextAccessor>().ActionContext;
            return new UrlHelper(actionContext);
        });

Now, you can inject IUrlHelper directly into anything that needs it without having to jump through IHttpContextAccessor .

Lee Oades
  • 1,638
  • 17
  • 24
  • 1
    This is great, because I need the UrlHelper in a service that has to be injected into the controller, so it needs to happen before I'm in the controller. Nice solution. – Tim Long Nov 22 '16 at 02:58
  • 1
    This works on .net core 2.2, but I had to change `IActionContextAccessor` to be `AddTransient` instead of `AddScoped` due to using `IUrlHelper.RouteUrl` in my consuming class – dan richardson Jul 26 '19 at 08:07
8

This method is now obsolete. Look at update below.

Instead of services.AddTransient<IUrlHelper, UrlHelper>() or trying to directly inject IUrlHelper you can inject IHttpContextAccessor and get the service from there.

public ClassConstructor(IHttpContextAccessor contextAccessor)
{
    this.urlHelper = contextAccessor.HttpContext.RequestServices.GetRequiredService<IUrlHelper>();
}

Unless it is just a bug, adding the IUrlHelper service with UrlHelper does not work.

UPDATE 2017-08-28

The previous method no longer seems to work. Below is a new solution.

Confgure IActionContextAccessor as a service:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddSingleton<IActionContextAccessor, ActionContextAccessor>()
        .AddMvc();
}

Then inject IActionContextAccessor and IUrlHelperFactory to then generate the IUrlHelper like below

public class MainController : Controller
{
    private IUrlHelperFactory urlHelperFactory { get; }
    private IActionContextAccessor accessor { get; }
    public MainController(IUrlHelperFactory urlHelper, IActionContextAccessor accessor)
    {
        this.urlHelperFactory = urlHelper;
        this.accessor = accessor;
    }

    [HttpGet]
    public IActionResult Index()
    {
        ActionContext context = this.accessor.ActionContext;
        IUrlHelper urlHelper = this.urlHelperFactory.GetUrlHelper(context);
        //Use urlHelper here
        return this.Ok();
    }
}
Gekctek
  • 1,161
  • 2
  • 12
  • 23
1

ASP.NET Core 2.0

Install

PM> Install-Package AspNetCore.IServiceCollection.AddIUrlHelper

Use

public void ConfigureServices(IServiceCollection services)
{
   ... 
   services.AddUrlHelper();
   ... 
}

Disclaimer: author of this package

tchelidze
  • 8,050
  • 1
  • 29
  • 49
0

FOR .NET CORE 3.1

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>()
                .AddScoped(x =>
                    x.GetRequiredService<IUrlHelperFactory>()
                        .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext)); //Inject UrlHelp for
  • 1
    Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes – Ran Marciano Feb 14 '21 at 05:49