Data transfer in startup.cs

How do you pass data to startup.cs?

This is for testing integration using WebHostBuilderandTestServer

I need to transfer different data depending on Test Fixture. Therefore, you do not want to extract it from the configuration file, for example

Data will be sent to registered middleware in startup.cs

The docs seem to suggest that this should work:

var configBuilder = new ConfigurationBuilder()
                .AddInMemoryCollection(new[]
                {
                    new KeyValuePair<string, string>("key", "value"),
                });

            var configuration = configBuilder.Build();

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseConfiguration(configuration) // config added here
                .UseStartup<Startup>()
                .Build();

            host.Run();

but when I check the Configuration object in startup.cs, the key is missing. And only the providers defined in startup.cs are available.

I am trying to do this in program.cs for the moment to test the concept, and then I will go over to integration tests later

Any ideas what I am doing wrong?

Is there a better way to pass data at startup?

+4
1

Startup Main. WebHostBuilder ConfigureServices, , ConfigureServices, Startup.

, ( , )

public class DataContainer
{
   public static string Test;
}

oneton

DataContainer.Test = "testing";

var host = new WebHostBuilder()
            .ConfigureServices(s => { s.AddSingleton(typeof(DataContainer)); })
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseConfiguration(configuration) // config added here
            .UseStartup<Startup>()
            .Build();

Startup ,

public Startup(IHostingEnvironment env, DataContainer data)
{
  // data.Test is available here and has the value that has been set in Main
}

, .

, , , , .

+1

Source: https://habr.com/ru/post/1679968/


All Articles