Search code examples
c#asp.net-coredependency-injection

How to invoke GetService from program.cs or bindings


I currently have my ISecretManager class dependency injected. I use this class to grab secrets stored in AWS.

I can use secrets to create more dependency injections

Services.AddScoped<IDbContext>(
    x => new DbContext(
        Context.Configuration,
        x.GetService<ISecretManager>().Get("DB")))

Now I am in a predicament. I need to enable Redis cache but the value is stored in secrets.

Services.AddStackExchangeRedisCache(options =>
{
    //secret value goes here
    options.Configuration = // GetService<ISecretManager>().Get("REDIS")
});

How do I get ISecretManager service invoke so I can populate Redis connection string? Can I also implement this in program.cs of my ASP.NET Core webapp?


Solution

  • var value = Services.BuildServiceProvider().GetService<ISecretManager>().Get("REDIS");
    Services.AddStackExchangeRedisCache(options => {
        options.Configuration = value;
    });