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();
}
}