Search code examples
c#flurl

How to register multiple Flurl clients in DI container?


Flurl documentation says that the recommended approach for Flurl clients using DI is to utilize this registration pattern:

// at service registration:
services.AddSingleton<IFlurlClientCache>(sp => new FlurlClientCache()
    .Add("MyCli", "https://some-api.com"));

However, this doesn't work if I need to repeat this code several times and register several clients into the DI container. Of course, I could chain many Add() methods and populate one cache with clients, but this is not always possible. Probable use-case - registration of different clients from different libraries.

Do you have any clues how to overcome this and properly register only one singleton IFlurlClientCache with multiple clients from multiple places in the code?


Solution

  • You're on the right track with GetOrAdd (per your self-answer), but you don't have to give up using DI to manage a singleton cache. It should end up looking more like this:

    // register the cache but don't add clients to it yet
    services.AddSingleton<IFlurlClientCache>(sp => new FlurlClientCache()
       .WithDefaults(b => {
            ...
        }));
    
    public class MyService
    {
        private static readonly IFlurlClient _flurlClient;
    
        public MyService(IFlurlClientCache flurlCache) {
            _flurlClient = flurlCache.GetOrAdd(serviceName, baseUri, configure);
        }
    }
    

    Even if the service above is registered as a transient, the named client will only get created and configured at most once, since the the cache is registered as a singleton.