Pass data to startup.cs

In ASP.NET Core 3, you can pass information as part of the configuration. In Program.cs, add a call to .UseSettings() and pass the configuration key and value as a string.

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder => {
        webBuilder.UseStartup<Startup>();
        webBuilder.UseSetting("CustomProperty", someProperty.ToString());
    })

Then, in your Startup.cs file, you should see the constructor defining a Configuration property.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    ...
}

Using that Configuration property, you can then access the value you passed from the Program.cs using .GetValue().

Configuration.GetValue<TObjectType>("CustomProperty");

One way to send data into the Startup would be to register a service in Main. WebHostBuilder has ConfigureServices method which can be used just like the ConfigureServices method you can implement in the Startup class.

For example you can make a class with static variables (not the best idea but works)

public class DataContainer
{
   public static string Test;
}

Then set its values and add it as a singleton service

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();

After this your Startup can just use the regular injection way to get this

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

The injection of course works in any class and method after this, not just the constructor.

I'm not sure if this is any better than to actually create a class with static values by itself but if the class needs to be changed sometimes it can be made into an interface and the other usual injection benefits.

Tags:

C#

.Net Core