gpt4 book ai didi

c# - 应用程序引发了未处理的异常。系统无效操作异常: Unable to > resolve service for type

转载 作者:行者123 更新时间:2023-12-02 04:24:07 25 4
gpt4 key购买 nike

我有一个简单的 asp.net core Web api,我试图仅使用 Visual Studio 模板默认附带的 api/值。但是我收到此错误:

Hosting environment: Production Content root path: C:\api.E-commerce Now listening on: http://localhost:18401 Application started. Press Ctrl+C to shut down. fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HL3RHG5NLHAL": An unhandled exception was thrown by the application. System.InvalidOperationException: Unable to resolve service for type 'ECommerce.Api.Repository.Ecommerce.IEcommerceRepository' while attempting to activate 'ContactsApi.Controllers.ValuesController'.
at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance[TInstance](IServiceProvider serviceProvider, Type implementationType) at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__22.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware
1.d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware
1.d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.d__2.MoveNext()

启动代码是:

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

更新1

值 Controller

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 异常!,日志文件中没有任何详细信息

最佳答案

错误消息表明 ValuesController正在被击中。在尝试实例化此 Controller 时 IEcommerceRepository在构造函数中使用。依赖注入(inject)框架正在尝试查找 IEcommerceRepository 类型的实现。 .

这应该注册在Startup.cs中。你可以这样注册: services.AddSingleton<IEcommerceRepository, MyEcommerceRepository>();在ConfigureServices 方法中。

关于c# - 应用程序引发了未处理的异常。系统无效操作异常: Unable to > resolve service for type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43215550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com