首页 文章

应用程序抛出了未处理的异常 . System.InvalidOperationException:无法>解析类型的服务

提问于
浏览
1

我有一个简单的asp.net核心web api,我试图只使用visual studio模板默认带来的api /值 . 但是我收到这个错误:

托管环境: 生产环境 内容根路径:C:\ api.E-commerce现在正在侦听:http:// localhost:18401应用程序已启动 . 按Ctrl C关闭 . 失败:Microsoft.AspNetCore.Server.Kestrel [13]连接ID“0HL3RHG5NLHAL”:应用程序抛出了未处理的异常 . System.InvalidOperationException:尝试激活“ContactsApi.Controllers.ValuesController”时无法解析类型“ECommerce.Api.Repository.Ecommerce.IEcommerceRepository”的服务 . 在Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance [TInstance]的lambda_method(Closure,IServiceProvider,Object [])上的Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired) IServiceProvider serviceProvider,Type implementationType)在Microsoft的Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&next,Scope&scope,Object&state,Boolean&isCompleted)的Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context)中 . AspNetCore.Mvc.Internal.ControllerActionInvoker.d__22.MoveNext()---抛出异常的前一个位置的堆栈跟踪结束---在Microsoft.AspNetCore.Mvc.Internal的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()处Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next中的.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)(状态和下一个,范围和范围, Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext()中的Object&state,Boolean&isCompleted)---从抛出异常的上一个位置开始的堆栈跟踪结束---在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw( )在Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)---从抛出异常的上一个位置的堆栈跟踪结束---在System.Runtime Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1中的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中的.ExceptionServices.ExceptionDispatchInfo.Throw() . <Invoke> d__18.MoveNext()---来自上一个位置的堆栈跟踪结束抛出异常---在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.d__18.MoveNext()的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中 - 堆栈跟踪结束从抛出异常的先前位置---在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()处 . <Invoke> d__18 . MoveNext()---从抛出异常的先前位置开始的堆栈跟踪结束---在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.d__18.MoveNext()的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中---结束来自抛出异常的先前位置的堆栈跟踪---在Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()处 . d__7.MoveNext()---抛出异常的前一个位置的堆栈跟踪结束---在Syst的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()处Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.d__7.MoveNext()中的em.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)---从抛出异常的上一个位置开始的堆栈跟踪结束---在System.Runtime Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.d__8.MoveNext()中的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中的.ExceptionServices.ExceptionDispatchInfo.Throw()---来自先前位置的堆栈跟踪结束被抛出---在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()atMicrosoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext()中的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)---从抛出异常的上一个位置的堆栈跟踪结束---在System.Runtime Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.d__2.MoveNext()中的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中的.ExceptionServices.ExceptionDispatchInfo.Throw()

启动代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Microsoft.EntityFrameworkCore;
using ContactsApi.Contexts;
using ECommerce.Api.Models.ERP;
using ECommerce.Api.Repository.ERP;
using System.IO;
//using Microsoft.AspNetCore.Mvc;
//using Microsoft.AspNetCore.Mvc.Cors.Internal;

namespace ContactsApi
{
    public partial class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

           // var host = new WebHostBuilder()
           //.UseKestrel()
           //.UseContentRoot(Directory.GetCurrentDirectory())
           //.UseIISIntegration() // IMPORTANT!!!
           //.UseStartup<Startup>()
           //.Build();
           // host.Run();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc()
                    .AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); ;

            //using Dependency Injection
            //services.AddSingleton<IContactsRepository, ContactsRepository>();
            //services.AddSingleton<ITodoTerrenoRepository, TodoTerrenoRepository>();

            services.AddDbContext<ContactsContext>(options =>
             options.UseSqlServer(Configuration.GetConnectionString("AuthentConnection")));
            services.AddDbContext<TODOTERRENOContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());
                options.AddPolicy("AllowAllHeaders", builder => builder.AllowAnyHeader());
                options.AddPolicy("AllowCredentials", builder => builder.AllowCredentials());
            });

            services.Configure<IISOptions>(options =>
            {

                options.AutomaticAuthentication = true;
                options.ForwardClientCertificate = true;
                options.ForwardWindowsAuthentication = true;


            });


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseCors("AllowAllOrigins");
            app.UseCors("AllowAllHeader");
            ConfigureAuth(app);
            //app.UseMvc(routes =>
            //{
            //    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            //});           
            //// Shows UseCors with CorsPolicyBuilder.
            //app.UseCors("AllowSpecificOrigin");
            app.UseMvc();
        }
    }
}

UPDATE 1

值控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using ECommerce.Api.Repository.Ecommerce;

namespace ContactsApi.Controllers
{
    //[Authorize]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {

        public IEcommerceRepository ContactsRepo { get; set; }


        public ValuesController(IEcommerceRepository _repo)
        {
            ContactsRepo = _repo;
        }
        // GET api/values
       // [HttpGet]
        //public IEnumerable<string> Get()
        //{


        //    ContactsRepo.CrearUsuario();

        //    return new string[] { "value1", "value2" };
        //}

       // [HttpGet]
        [HttpGet("{DatosUsuario}")]
        public string GestionarUsuario(string DatosUsuario)
        {



            return ContactsRepo.GestionarUsuario(DatosUsuario).Result;
        }

        // GET api/values/5
        [HttpGet]
       // public string Get(in)
        public string Get()
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

UDPATE 2

现在我们得到Stackoverflow异常!,日志文件中根本没有任何细节

2 回答

  • 1

    看来你没有注册 EcommerceRepositoryIEcommerceRepository .

    例如,

    public void ConfigureServices(IServiceCollection services)
    {
       ...
       services.AddTransient<IEcommerceRepository, EcommerceRepository>();
       ...
    }
    
  • 3

    错误消息表明正在命中 ValuesController . 在尝试实例化此控制器时, IEcommerceRepository 在构造函数中使用 . 依赖注入框架试图找到 IEcommerceRepository 类型的实现 .

    这应该在 Startup.cs 中注册 . 您可以在ConfigureServices方法中注册类似于: services.AddSingleton<IEcommerceRepository, MyEcommerceRepository>(); 的内容 .

相关问题