Storing Application Variables
asp.net, asp.net-mvc, session
Solution
In order:
Global.asax.cs
- Pros: Works in all ASP.NET apps, available statically so you don't have to flow the data around the app yourself.
- Cons: Not strongly-typed. Doesn’t automatically work in distributed environment.
OWIN
- Pros: Works great in OWIN and flows across the app. Using statics is considered poor programming by some.
- Cons: Doesn't work if you're not using OWIN (e.g. Katana). Doesn’t automatically work in distributed environment.
Static Container
- Pros: Works in all ASP.NET apps, available statically. Strongly-typed means no ugly casts
- Cons: It's static :) Doesn’t automatically work in distributed environment.
Database
- Pros: Works in a distributed system
- Cons: Potentially very slow; can fail due to network issues; requires a lot more code to implement reliably. The data must also be serializable.
Cache
- Pros: Similar to database, except much faster.
- Cons: Similar to database (but much faster), plus the cache isn't generally meant for long-lived objects, though the ASP.NET cache does offer that behavior (but at that point, why use the cache).
Problem
There seems to be three distinct methods of storing a variable that will be available for every request in an application: Global.asax.cs ``` public class MvcApplication : HttpApplication { protected void Application_Start() { Application["SiteDatabase"] = new SiteDatabase(); } } ``` OWIN: ``` public partial class Startup { public void ConfigureAuthentication(IAppBuilder Application) { Application.CreatePerOwinContext<SiteDatabase>(new SiteDatabase()); } } ``` Static Container ``` public static class GlobalVariables { private SiteDatabase _Database; public SiteDatabase Database { get { return _Database ?? new SiteDatabase(); } } } ``` What are the relative advantages of each method?