title: An unhandled exception was thrown by the application. System.InvalidOperationException: Unable to > resolve service for type
body: <p>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:</p>
  
  <blockquote>
    <p>Hosting environment: Production Content root path: C:\api.E-commerce
    Now listening on: <a href="http://localhost:18401" rel="noreferrer">http://localhost:18401</a> 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'.<br>
    at
    Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider
    sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)<br>
    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&amp;
    next, Scope&amp; scope, Object&amp; state, Boolean&amp; 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&amp;
    next, Scope&amp; scope, Object&amp; state, Boolean&amp; 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.AuthenticationMiddleware<code>1.&lt;Invoke&gt;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</code>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.AuthenticationMiddleware<code>1.&lt;Invoke&gt;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</code>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()</p>
  </blockquote>
  
  <p>the startup code is:</p>
  
  <pre><code>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&lt;Startup&gt;()
             //.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 =&gt; a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); ;
  
              //using Dependency Injection
              //services.AddSingleton&lt;IContactsRepository, ContactsRepository&gt;();
              //services.AddSingleton&lt;ITodoTerrenoRepository, TodoTerrenoRepository&gt;();
  
              services.AddDbContext&lt;ContactsContext&gt;(options =&gt;
               options.UseSqlServer(Configuration.GetConnectionString("AuthentConnection")));
              services.AddDbContext&lt;TODOTERRENOContext&gt;(options =&gt;
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
              services.AddCors(options =&gt;
              {
                  options.AddPolicy("AllowAllOrigins", builder =&gt; builder.AllowAnyOrigin());
                  options.AddPolicy("AllowAllHeaders", builder =&gt; builder.AllowAnyHeader());
                  options.AddPolicy("AllowCredentials", builder =&gt; builder.AllowCredentials());
              });
  
              services.Configure&lt;IISOptions&gt;(options =&gt;
              {
  
                  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 =&gt;
              //{
              //    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
              //});           
              //// Shows UseCors with CorsPolicyBuilder.
              //app.UseCors("AllowSpecificOrigin");
              app.UseMvc();
          }
      }
  }
  </code></pre>
  
  <p><strong>UPDATE 1</strong></p>
  
  <p>values controller</p>
  
  <pre><code>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&lt;string&gt; 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)
          {
          }
      }
  }
  </code></pre>
  
  <p><strong>UDPATE 2</strong></p>
  
  <p>Now we get Stackoverflow exception!, with no details at all in the log file</p>