Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.MVC application constants, what is the best/most elegant approach?

Simple question really,

I am just looking for community support what works best architecturally.

Say, following case: TempData["MySetting"]? Where should I store "MySetting"? Should it be

  1. in separate class so that the access will be TempData[Config.MySetting];
  2. in web.config so that the access is TempData[ConfigurationManager.AppSettings["MySetting"];
  3. inline, leave it as string TempData["MySetting"];?
  4. in the DB in some constants table, so that

    var mySetting = (string)_db.GetConstant("MySetting");
    TempData[mySetting];
    

I would not deal with option 4, just brought it for completeness of the picture. So what do you suggest and why?

Edit Question is rather general about constants in asp mvc rather than TempData case.

Thanks.

like image 585
Display Name Avatar asked Dec 07 '22 13:12

Display Name


2 Answers

In your particular case you should make a wrapper around TempData which will expose your data as property. All the access to TempData should be hidden inside that wrapper. In this case all the usages of "MySetting" will be limited to at most two. If there's only one usage, you don't need to do anything. If there're two - you define your "MySetting" as private const field.

In short:

public static class TempDataWrapper
{
    private const string _mySettingName = "MySetting";

    public int MySetting
    {
        get { return (int) TempData[_mySettingName];}
        set { TempData[_mySettingName] = value;}
    }
}

For the sake of brevity we are not dealing here with coupling (which is tight) and error-handling (which is none).

like image 86
Serg Rogovtsev Avatar answered Feb 15 '23 06:02

Serg Rogovtsev


I would go with:

public static class Config
{
    public static readonly string MyValue = "SomeValue";
}

More about Const vs Readonly

like image 42
formatc Avatar answered Feb 15 '23 07:02

formatc