I have a simple asp.net core web api and I am trying to consume just the api/values that comes by default with the visual studio template. however I get this error:
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()
the startup code is:
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
values 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
Now we get Stackoverflow exception!, with no details at all in the log file
Dependency Injection (DI) is a software design pattern that allows us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.
Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.
AddScoped(IServiceCollection, Type, Type) Adds a scoped service of the type specified in serviceType with an implementation of the type specified in implementationType to the specified IServiceCollection.
Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.
The error messages indicates that the ValuesController
is being hit. While trying to instantiate this controller the IEcommerceRepository
is used in the constructor.
The dependency injection framework is trying to find an implementation of the type IEcommerceRepository
.
This should be registered in the Startup.cs
. You can register it something like:
services.AddSingleton<IEcommerceRepository, MyEcommerceRepository>();
in the ConfigureServices method.
It seems that you did not register EcommerceRepository to IEcommerceRepository.
For example,
public void ConfigureServices(IServiceCollection services)
{
...
services.AddTransient<IEcommerceRepository, EcommerceRepository>();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With