17

Created a blank ASP.NET Core 2.0 application. In Startup.cs, would like to log incoming requests. So in configure method, I am using Microsoft.Extensions.Logging.ILogger

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger logger)
  {    
      app.Use(next =>
        {
            return async context =>
            {
                logger.LogInformation("Incoming request");
                await next(context);
                logger.LogInformation("Outgoing response");
            };
        });

However, when I build the project, its complaining

 An error occurred while starting the application.
 InvalidOperationException: No service for type 'Microsoft.Extensions.Logging.ILogger' has been registered.

Why and how should I register this service? Had it been my interface, it would have still made sense to do

services.AddScope

in ConfigureServices

blue piranha
  • 3,706
  • 13
  • 57
  • 98
  • Possible duplicate of [Why ASP.NET Core DI knows how to resolve ILogger, but not ILogger?](https://stackoverflow.com/questions/38255053/why-asp-net-core-di-knows-how-to-resolve-iloggert-but-not-ilogger) – Set Mar 17 '18 at 16:37

2 Answers2

29

ILogger is always of a type, try change it like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
  {    
      app.Use(next =>
        {
            return async context =>
            {
                logger.LogInformation("Incoming request");
                await next(context);
                logger.LogInformation("Outgoing response");
            };
        });
Joe Audette
  • 35,330
  • 11
  • 106
  • 99
  • If I have a Helpers class that is called from different types, like a Controller, View or another helper class, will I need different Helpers constructor for each calling type? Like `Helpers(ILogger logger, IConfiguration configuration)` and `Helpers(ILogger logger, IConfiguration configuration)`? – joym8 Aug 13 '20 at 15:50
0

No service for type 'Microsoft.Extensions.Logging.ILogger' has been registered

This error means that you didn't provide class name into your logger interface(instance of the interface), for example instead of:

ILogger logger

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger logger)
  {   

You should use:

ILogger<Startup> logger

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
  {   
Lev K.
  • 344
  • 4
  • 4