繁体   English   中英

尝试激活时无法解析类型为“ Microsoft.AspNetCore.Mvc.IUrlHelper”的服务

[英]Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' while attempting to activate

我试图将代码从控制器分离到我创建的服务。 我所做的是使用接口IUserService创建用户服务。

将RegisterUser代码从直接控制器移到UserService,我遇到的下一个挑战是,直接与Controller一起使用的Url与Service不一起使用。

从控制器到服务的此代码已更改为:

如果在控制器中

var callbackUrl = Url.EmailConfirmationLink(user.Email, token, model.contactno, Request.Scheme);

从控制器更改为服务:

  private IUrlHelper _urlHelper;

    public UserService (IUrlHelper urlHelper, HttpRequest request) {
_urlHelper = urlHelper;
}

这是构造函数,

在方法中,我这样称呼它:

        var callbackUrl = _urlHelper.EmailConfirmationLink (user.Email, token, U.Email, _request.Scheme);

我在Startup.cs的DI中提到了这样的内容:

services.AddScoped<IUserService, UserService>();

编译时没有例外。 在运行时,它抛出以下异常:

Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' while attempting to activate 'erp.Services.UserService'.

不太清楚到底需要做什么。

这是完整的堆栈跟踪,可以更仔细地查看错误。 好吧,我不能说确切的行,因为我不是在调试,而只是从日志中复制:

Executed endpoint 'erp.Controllers.AccountController.Register (erp)'
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpRequest' while attempting to activate 'erp.Services.UserService'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)

像这样在您的DI容器中注册IUrlHelper

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

要在服务中使用HttpContext,必须使用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;
    }
}

另外,不要忘记在您的DI容器中注册IHttpContextAccessor:

services.AddHttpContextAccessor();

对于Object reference not set to an instance of an object ,这是由于未注册IActionContextAccessor

请尝试执行以下步骤:

  1. 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(); } } 
  2. 寄存器

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM