I am just learning to use ASP.NET Core after not doing any development in C# for several years. The built-in dependency injection is really nice, but can lead to some confusion at times. I was trying to inject an ILogger
into a constructor and had this error:
public RequestLogger(ILogger logger, ICurrentUserService currentUserService)
{
_logger = logger;
_currentUserService = currentUserService;
}
InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'RequestLogger....
After trying to debug it for a while and getting nowhere, I ran across this on Stack Overflow from Hooman Bahreini:
What should be injected (at least according to the article above) is a non-generic ILogger, but then, that's not something that Microsoft's Built-in DI Container can do, and you need to use a 3rd party DI Library.
So I changed the code to this:
public RequestLogger(ILogger<RequestLogger> logger, ICurrentUserService currentUserService)
{
_logger = logger;
_currentUserService = currentUserService;
}
This solved the problem. Either always specify the type of the logger in the generic type parameter or use another injection framework than the built-in one.