2

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?}");
        });
    }
}
1
  • Store in a config file or you can always pull them from a database table. Commented Sep 13, 2018 at 19:21

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

6 Comments

I like to use the scope of user if it is for a printer, because everyone might have a different printer name. I like to use the application scope if it is going to be non changeable across the app and I'll call it like this Properties.Settings.Default.SalesOrg.Trim()
This is for ASP.NET. The OP is using ASP.NET Core.
Okay then what's your answer, Chris?
Not sure what the attitude is about. This isn't a reasonable people can disagree or even just one way is better than another situation. ApplicationSettings relies on Web.config, which is totally unsupported in ASP.NET Core. Your answer literally doesn't work at all. The Settings tab doesn't even exist in the properties for an ASP.NET Core project.
No attitude. You are just saying I'm wrong without answering the question. What version of visual studio are you working with? What year? What is your .NET framework version?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.