Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' while attempting to activate
For Object reference not set to an instance of an object
, it is caused by that you did not register IActionContextAccessor
.
Try follow steps below:
UserService
public interface IUserService { void RegisterUser(); } public class UserService : IUserService { private IUrlHelper _urlHelper; private HttpRequest _request; public UserService(IUrlHelper urlHelper, IHttpContextAccessor httpContextAccessor) { _urlHelper = urlHelper; _request = httpContextAccessor.HttpContext.Request; } public void RegisterUser() { var callbackUrl = _urlHelper.EmailConfirmationLink("user.Email", "token", _request.Scheme); //throw new NotImplementedException(); } }
Register
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); services.AddScoped<IUrlHelper>(x => { var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext; var factory = x.GetRequiredService<IUrlHelperFactory>(); return factory.GetUrlHelper(actionContext); }); services.AddScoped<IUserService, UserService>();
Register IUrlHelper
in your DI Container like this :
services.AddScoped<IUrlHelper>(factory =>
{
var actionContext = factory.GetService<IActionContextAccessor>()
.ActionContext;
return new UrlHelper(actionContext);
});
And to use HttpContext in your services, you must use IHttpContextAccessor:
public class MyService
{
private IHttpContextAccessor _httpContextAccessor;
public MyService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void MyMethod()
{
// Use HttpContext like this
var username = _httpContextAccessor.HttpContext.User.Identity.Name;
}
}
Also, don't forget to register IHttpContextAccessor in your DI Container :
services.AddHttpContextAccessor();