MVC 6 IUrlHelper Dependency Injection

Gekctek picture Gekctek · Jun 25, 2015 · Viewed 7.4k times · Source

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.

Answer

Lee Oades picture Lee Oades · Nov 1, 2016

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 .