依赖注入 .NET Core - InvalidOperationException

Dependency Injection .NET Core - InvalidOperationException

我正在学习 .NET Core,我正在尝试在 startup.cs 中使用 IServiceCollection 来解决我的依赖关系。我在我的控制器中注入了一个依赖项,并且该依赖项被解析为 class ,它也有一个注入的依赖项。基本上我得到一个 InvalidOperationException 因为它无法激活依赖项。

这是我的堆栈跟踪:

InvalidOperationException: Unable to resolve service for type 'TestApplication.Services.LoginHttpService' while attempting to activate 'TestApplication.Services.LoginService'.

    Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet<Type> callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)   

    Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet<Type> callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet<Type> callSiteChain)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet<Type> callSiteChain)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet<Type> callSiteChain)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider)
    System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd<TKey, TValue, TArg>(ConcurrentDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg arg)
    Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
    Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
    lambda_method(Closure , IServiceProvider , Object[] )
    Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance<TInstance>(IServiceProvider serviceProvider, Type implementationType)
    Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__18.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__18.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware+<ExecuteWithFilter>d__7.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

我的启动 class 具有已注册的依赖项:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    // Added - uses IOptions<T> for your settings.
    services.AddOptions();

    // Added - Confirms that we have a home for our DemoSettings
    services.Configure<UrlConfigurations>(Configuration.GetSection("UrlConfigurations"));

    //services.AddSingleton<ITokenProvider, Tokenpro>();

    services.AddTransient<ILoginService, LoginService>();
    services.AddSingleton<IHttpService, HttpService>();
    services.AddSingleton<ILoginHttpService, LoginHttpService>();

    services.AddSingleton<IUrlConfigurations, UrlConfigurations>();
    services.AddSingleton<IJsonDeserializer, JsonDeserializer>();
    services.AddSingleton<IHttpClientFactory, HttpClientFactory>();

    services.AddSingleton<IJsonValidator, JsonValidator>();
}

我将在解决运行时错误后将作用域(瞬态、单例等)更改为正确的类型。

我的登录控制器:

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using TestApplication.Configurations;
using TestApplication.Interfaces.Configurations;
using TestApplication.Interfaces.Services;
using TestApplication.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace TestApplication.Controllers
{
    public class LoginController : Controller
    {
        private readonly ILoginService _loginService;
        private readonly IUrlConfigurations _urlConfigurations;

        public LoginController(ILoginService loginService, IOptions<UrlConfigurations> urlConfigurations)
        {
            _loginService = loginService;
            _urlConfigurations = urlConfigurations.Value;
        }

        public async Task<IActionResult> Index()
        {
            var jsonWebToken = await GetJsonWebToken();
            return View();
        }

        private async Task<JwtSecurityToken> GetJsonWebToken()
        {
            // get token - hard-coded for now
            var login = new LoginViewModel { Username = "xsurajit.kar@thomastelford.comx", Password = "marshwall" };
            var jsonWebToken = await _loginService.Login(login);
            return jsonWebToken;
        }
    }
}

我的登录服务使用LoginHttpService:

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using TestApplication.Configurations;
using TestApplication.Interfaces.Configurations;
using TestApplication.Interfaces.Services;
using TestApplication.Models;

namespace TestApplication.Services
{
    public class LoginService : ILoginService
    {
        private readonly LoginHttpService _loginHttpService;
        private readonly IUrlConfigurations _urlConfigurations;

        public LoginService(LoginHttpService loginHttpService, IOptions<UrlConfigurations> urlConfigurations)
        {
            _loginHttpService = loginHttpService;
            _urlConfigurations = urlConfigurations.Value;

        }

        public async Task<JwtSecurityToken> Login(LoginViewModel login)
        {
            login.LoginMapper();
            var response = await _loginHttpService.PostLoginAsync(_urlConfigurations.GetToken, login.EncodedLoginDetailsContent);

            if (response == null) return null;

            var data = await response.Content.ReadAsStringAsync();
            // Deserialize JWT
            var accessToken = JsonConvert.DeserializeObject<UserResponseModel>(data)?.access_token;

            if (string.IsNullOrEmpty(accessToken) || !response.IsSuccessStatusCode) return null;

            // Cast JWT to correct class
            var securityToken = new JwtSecurityTokenHandler().ReadToken(accessToken) as JwtSecurityToken;

            return securityToken;
        }
    }
}

有谁知道我在 startup.cs class 中做错了什么?我想解析在 TestApplication.Services.LoginService.

中使用的 TestApplication.Services.LoginHttpService
public LoginService(LoginHttpService loginHttpService, IOptions<UrlConfigurations> urlConfigurations)
{
    _loginHttpService = loginHttpService;
    _urlConfigurations = urlConfigurations.Value; 
}

LoginService class 构造函数中的 LoginHttpService 更改为接口 ILoginHttpService

这应该有效。

就我而言,我忘记在 Startup.cs 中添加上下文服务:

services.AddDbContext<My_ScaffoldingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));