Inject ILogger when adding a Singleton for Azure Functions 3.0

Viewed 971

I have a redisprovider class in my Azure Function:

        public RedisCacheProvider(ILogger<RedisCacheProvider> logger,
            IConnectionMultiplexer connectionMultiplexer)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            multiplexer = connectionMultiplexer;
        }

I am adding this class as a singleton but how do I initialise the Ilogger in the startup class. I am aware it is injected by Azure Functions into the classes. If so, how do I manage this in the startup class when we need to initialise other objects for the class on startup?

 services.AddSingleton<ICacheProvider>(serviceProvider =>
                    new RedisCacheProvider(**???**, serviceProvider.GetRequiredService<IConnectionMultiplexer>()));

Usually, I do this:

services.AddSingleton<IHttpService, HttpService>();

In the RedisProvider class, I need to pass my connection string. So how do I inject the ILogger when I pass the IConnectionMultiplexer?

2 Answers

If I understand correctly, you need to manage construction manually, since you need to inject settings. This raises the question of how to inject the subdependencies, which is normally managed by the container.

Actually, we can acquire the subdependencies just like you already do for the multiplexer!

services.AddSingleton<ICacheProvider>(serviceProvider => new RedisCacheProvider(
    serviceProvider.GetRequiredService<ILogger>(),
    serviceProvider.GetRequiredService<IConnectionMultiplexer>()));

I would try to avoid creating singletons like that. Instead of passing the connection string, consider passing IOptions<RedisOption> to your RedisCacheProvider in order to access the connection string within the constructor. This would also allow you to register your service like this:

services.AddSingleton<ICacheProvider, RedisCacheProvider>()

Further reading: Options pattern in ASP.NET Core

Related