Search code examples
c#asp.netasp.net-core

get the ServiceKey value from a within a KeyedService implementation


I have a KeyedService, sometimes injected as Singleton if the page is anonymous, and other times as Scoped if the page requires authentication.

builder.Services.AddKeyedSingleton<IClientService, ClientService>(Constants.Singleton) ; 
builder.Services.AddKeyedScoped<IClientService, ClientService>(Constants.Scoped);

within the ClientService implementation, I would like to know which ServiceKey was used to retrieve the instance, so that I change the details of the code within the constructor accordingly.

I'm not finding any way that I can get the value of the ServiceKey that was used to obtain the ClientService instance. Anyone have any ideas?

ps, just in case anyone is reading, this post is not the same question.


Solution

  • ServiceProvider does not natively expose the key to the service instance. A workaround here is to add key parameter when create the service so you could access.

        public interface IClientService
        {
            string GetKey();
        }
    
        public class ClientService : IClientService
        {
            private readonly string _key;
    
            public ClientService(string key)
            {
                _key = key;
            }
    
            public string GetKey() => _key;
        }
    

    Register

    builder.Services.AddKeyedSingleton<IClientService, ClientService>("key1", (sp, key) => new ClientService("key1"));
    builder.Services.AddKeyedSingleton<IClientService, ClientService>("key2", (sp, key) => new ClientService("key2"));