Initializing a global static dictionary from a database in Webapi

I want to initialize a global dictionary from a database in my web api. Do I need to embed my DBContext in Global.Asax or Owin Startup. Any example would be much appreciated.

+4
source share
2 answers

Initialization targets of any type can be made in your custom OWIN startup class class, for example:

using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using Owin; using System; [assembly: OwinStartup(typeof(WebAPIRestWithNest.Startup))] namespace YourNamespace { public class Startup { public Dictionary<string, string> Table {get; private set;} public void Configuration(IAppBuilder app) { // token generation app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AllowInsecureHttp = false, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(8), Provider = new SimpleAuthorizationServerProvider() }); // token consumption app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); app.UseWebApi(WebApiConfig.Register()); Table = ... Connect from DB and fill your table logic ... } } } 

After that, you can use your Startup.Table property from your application.

+4
source

In general, it is bad practice to access objects using a static field in asp.net applications, as this can lead to errors that are hardly detected and reproduced: this is especially true for objects that are not subject to a constant / non-thread like a dictionary.

I assume that you want to cache some database data in memory to avoid excessive SQL queries. For this purpose, we recommend using standard asp.net caching:

 public IDictionary GetDict() { var dict = HttpRuntime.Cache.Get("uniqueCacheKey") as IDictionary; if (pvtData==null) { dict = doLoadDictionaryFromDB(); // your code that loads data from DB HttpRuntime.Cache.Add(cacheKey, dict, null, Cache.NoAbsoluteExpiration, new TimeSpan(0,5,0), // cache at least for 5 minutes after last access CacheItemPriority.Normal, null); } return dict; } 

This approach allows you to choose the appropriate expiration policy (without having to reinvent the wheel with a static dictionary).

If you still want to use a static dictionary, you can put it at the top of the application (global.asax):

 void Application_Start(object sender, EventArgs e) { // your code that initializes dictionary with data from DB } 
+2
source

All Articles