After upgrading to ASP.NET Core 2.0 the following code started to fail:
In my HomeController, I have a this new piece of code added;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HomeController : Controller | |
{ | |
private readonly ILogger _logger; | |
public HomeController(ILogger logger) | |
{ | |
_logger = logger; | |
} | |
} |
Instead of getting my HomeController back with an instance of ILogger injected into it, I got the following error message:
InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyApp.Web.Controllers.HomeController'.
This code worked before but refuses to work in ASP.NET Core 2.0.
Someone mentioned me to try the following instead:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private readonly ILogger _logger; | |
public HomeController(ILogger<HomeController> logger) | |
{ | |
_logger = logger; | |
} |
And indeed this worked. It turns out that the ILogger interface is no longer registered in the IoC container. Instead you have to always resolve an ILogger<T>. I have no clue why they did this change…