Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register ILogger for injection in ASP.NET MVC 6

I have a ASP.NET MVC 6 (beta-4) app.

public void ConfigureServices(IServiceCollection services) {     // Logging     services.AddLogging();      // ... }  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) {     // Add the console logger.     loggerfactory.AddConsole(minLevel: LogLevel.Warning);      // ... } 

And I have a controller...

public class HomeController :      Controller {     ILogger _logger;      public HomeController(ILogger logger)      {         _logger = logger;     }      // ... } 

But when I'm not getting the service registered correctly somehow: InvalidOperationException: Unable to resolve service for type 'Microsoft.Framework.Logging.ILogger' while attempting to activate 'HomeController'.. What am I doing wrong with the registering the logger?

like image 675
Travis Avatar asked May 12 '15 15:05

Travis


People also ask

What is net core logger?

Logging providers store logs, except for the Console provider which displays logs. For example, the Azure Application Insights provider stores logs in Azure Application Insights. Multiple providers can be enabled. The default ASP.NET Core web app templates: Use the Generic Host.

What is model binding in ASP.NET Core?

Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.


1 Answers

I assumed that services.AddLogging(); was doing the right thing and registering ILogger. After looking at the source (https://github.com/aspnet/Logging/blob/d874c5726e713d3eb34938f85faf7be61aae0f2a/src/Microsoft.Framework.Logging/LoggingServiceCollectionExtensions.cs) I found that it's actually registering ILogger<>. Changing the signature of ILogger to ILogger<HomeController> makes the above example work.

public class HomeController :      Controller {     ILogger<HomeController> _logger;      public HomeController(ILogger<HomeController> logger)      {         _logger = logger;     }      // ... } 

Thanks to @Steve for setting me on the right track to find this.

like image 145
Travis Avatar answered Sep 16 '22 15:09

Travis