1

I have two values that are in the database and define the behavior of too many things in my application and will not change at least in the near future. Is the best decision to create a static variables and load the values in Global.asax of my application??.

Jorge
  • 17,896
  • 19
  • 80
  • 126

4 Answers4

1

A general rule is, use cache when you know that your values/data will expire or require a change after certain time period otherwise use static variables. I found a similar discussion HttpRuntime.Cache[] vs Application[]
Also check out ASP.NET Caching: Techniques and Best Practices

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
0

Yes, you can cache them in a static variable. But if they don't need to change now and they stay the same, why don't you define them as constants or in web.config?

MikeSW
  • 16,140
  • 3
  • 39
  • 53
0

I would suggest to create a static class with properties these constant settings of yours that will set its values from the database once in the start up of your application.

I am doing the same thing whenever I have "system" settings that are stored in the database. I keep them in a static class as properties and access them all the time. I also use the same technique for the contents of small tables (i.e. item groups) that do not change often but used a lot in order to reduce database traffic. I create read only collections and access them instead of hit the database all the time.

But anything is a matter of what fits you best, as long as it is clean and easy to maintain.

Dummy01
  • 1,985
  • 1
  • 16
  • 21
0

Personally I use dependency injection for my MVC sites (ninject is the one I prefer). This allows you to define a variable as .InSingletonScope which means that you don't need to have nasty statics hanging around in your application. I then load the value from the DB on first request and store it in a local variable and its nice and tidy.

ie i would use this:

public class CachedFooProperty : IFooProperty
{
   public CachedFooProperty(IRepository<Foo> fooRepo)
   {
      Foo = fooRepo.GetFoo();
   }
   public Foo Foo{get;private set;}
}

and then bind it like this:

Bind<IFooProperty>().To<CachedFooProperty>().InSingletonScope();

The nice thing about this way of doing things is its really easy to turn on and off caching by simply changing the bindings. You could also really easially change this to an web.config based config method without changing every place you use the setting.

undefined
  • 33,537
  • 22
  • 129
  • 198