Home > Software engineering >  How to pass in settings into a class (derived ASP.NET Core Startup.cs) from ConfigureServices in a t
How to pass in settings into a class (derived ASP.NET Core Startup.cs) from ConfigureServices in a t

Time:01-18

I basically have this code

[Fact]
public async Task Test()
{
   var settings = new MySettings() { Name = "Jhon" }; //<-- use this

   var webHostBuilder = new WebHostBuilder()
    .UseStartup<TestStartup>()
    .ConfigureServices(services =>
    {
        // this is called...
        services.AddSingleton(settings);
    });
       
     //omitted code.. 
 }

And I want to be able to use MySettings in the TestStartup.

Whatever I try just returns Name == null..

I have tried this

public class TestStartup : Startup
{
    public TestStartup(IConfiguration configuration) : base(configuration)
    {
       Configuration = configuration;

       // Name is always != "Jhon"

       // doesn't work
       var mySettings = configuration.Get<MySettings>();

       // doesn't work either
       var mySettings = new MySettings();
       configuration.Bind("MySettings", mySettings);

       // tried various other things that didn't work
    }
}

What am I missing?

CodePudding user response:

You can leverage the MemoryConfigurationProvider:

using Microsoft.Extensions.Configuration;

var webHostBuilder = new WebHostBuilder()
    .ConfigureAppConfiguration(configurationBuilder => configurationBuilder
        .AddInMemoryCollection(new Dictionary<string, string?>
        {
            { "Name", "Jhon" },
            {"Logging:LogLevel:Default", "Warning"}
        }))
    .UseStartup<TestStartup>()
    // ...

and then it can be consumed with any standard pattern for configuration, for example:

public class TestStartup : Startup
{
    public TestStartup(IConfiguration configuration) : base(configuration)
    {
       var nameKeyValue = Configuration["Name"];
    }
}
  • Related