Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject ILogger when adding a Singleton for Azure Functions 3.0

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?

like image 929
Nilay Avatar asked Aug 17 '20 07:08

Nilay


1 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>()));
like image 183
Timo Avatar answered Sep 28 '22 21:09

Timo