Injecting ILogger<T> in Azure Functions throws an Exception
See original GitHub issueIn an Azure Function, an instance of ILogger
is injected in the functions themselves. But I would like to inject an instance of ILogger
/ ILogger<T>
/ ILoggerFactory
in my components registered with SimpleInjector. Doing so results in the following exception:
System.Private.CoreLib: Exception while executing function: TestGenericLogger. SimpleInjector: The registered delegate for type ILogger<GenericSpeaker> threw an exception. Unable to resolve service for type ‘Microsoft.Azure.WebJobs.Script.IFileLoggingStatusManager’ while attempting to activate ‘Microsoft.Azure.WebJobs.Script.Diagnostics.HostFileLoggerProvider’. Microsoft.Extensions.DependencyInjection: Unable to resolve service for type ‘Microsoft.Azure.WebJobs.Script.IFileLoggingStatusManager’ while attempting to activate ‘Microsoft.Azure.WebJobs.Script.Diagnostics.HostFileLoggerProvider’.
The full example can be found on this repo: https://github.com/ahocquet/simple-injectore-af-logging
Here’s a sample of my code:
[FunctionName("TestGenericLogger")]
public static IActionResult TestGenericLogger(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
HttpRequest req,
ILogger log)
{
DIConfig.Container.GetInstance<GenericSpeaker>().SayHello();
return new OkResult();
}
The registration process looks like this:
public static class DIConfig
{
public static readonly Container Container = new Container();
public static void Init(IServiceCollection serviceCollection)
{
serviceCollection.AddSimpleInjector(Container);
Container.Register<Speaker>();
Container.Register<GenericSpeaker>();
Container.Register<FactorySpeaker>();
serviceCollection.BuildServiceProvider()
.UseSimpleInjector(Container);
}
}
The dependency injection using IServiceCollection
works great for ILogger<T>
and ILoggerFactory
. Therefore, there must be a way to crosswire the ILoggerFactory
/ ILogger<T>
.
I could apply a composition root pattern and use an entry point in all my functions that will set the ILogger
instance within a LoggingWrapper
service. That would work, but that would let me unsatisfied. 🤔
Issue Analytics
- State:
- Created 4 years ago
- Comments:10
Simple Injector is not able to inject dependencies into Azure functions and I advise not using method injection at all. We have other Azure-related questions on this forum that discuss this as well. Take a look.
I created a new Azure Functions Integration page. This demonstrates how to integrate Simple Injector with Azure Functions v3.