Set Dynamic Variables in Startup.cs in ASP.NET CORE

Viewed 5055

I'm having trouble understanding the best way to SET dynamic variables in the Startup.cs. I want to be able to GET that value in a Controller OR in a View. I want to be able to store the values in memory, not a JSON file. I've looked into setting values into a session variables, but that does not seem to be good practice or work. What is best practice to set dynamic variables in the Startup.cs?

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

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        //services.AddDbContext<>(options => options.UseSqlServer(Configuration.GetConnectionString("Collections_StatsEntities")));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
2 Answers

Globals and statics are bad. ASP.NET Core includes DI built-in specifically to avoid these, so don't go and reintroduce them. The correct approach is to use configuration. Out of the box, an ASP.NET Core app supports configuration via JSON (appsettings.json and appsettings.{environment}.json), command-line, user secrets (also JSON, but stored in your profile, rather than in-project), and environment variables. If you need other sources of configuration, there's other existing providers available, or you can even roll your own to use whatever you like.

Whichever config source you use, the end result will be all the configuration settings from all sources going into IConfigurationRoot. While you can technically use that directly, it's better to use the strongly-typed configuration provided by IOptions<T> and similar. Simply, you create a class that represents some section in your config:

public class FooConfig
{
    public string Bar { get; set; }
}

Which would correspond to something like { Foo: { Bar: "Baz" } } in JSON, for example. Then, in ConfigureServices in Startup.cs:

services.Configure<FooConfig>(Configuration.GetSection("Foo"));

Finally, in your controller, for example:

 public class FooController : Controller
 {
     private IOptions<FooConfig> _config;

     public FooController(IOptions<FooConfig> config)
     {
         _config = config ?? throw new ArgumentNullException(nameof(config));
     }

     ...
 }

Configuration is read at startup, and technically exists in memory afterwards, so your complaint about having to use something like JSON is meaningless for the most part. However, if you truly want completely in-memory, there is a memory configuration provider. However, it's always better to externalize your config if you can.

Well, double click your settings.settings in your properties before you compile your code. you can give the variable a name, a type, a scope (user is means that it can be changed per installation, application means it will stay the way it is with the original value and cannot be changed), and lastly the value.

Related