I have a class called DataPoint that is defined like the following. Currently, i
ID: 646074 • Letter: I
Question
I have a class called DataPoint that is defined like the following. Currently, it goes through each property on an object and based on the DataPoint, it does some formatting like padding, trimming, etc... before it will save the record to the database. The current implementation makes a database call for each property which is slow, so my first step is to get everything at once into an in-memory collection. What else can I do below? Is this a good candidate for a singleton since the data rarely changes and/or is it possible to cache it (if so, how)?
public class DataPoint
{
public string Name {get;set;}
public string Justification {get;set;}
public int MaxLength {get;set;}
public string Format {get;set;}
public DataPoint GetDataPoint(string name)
{
var dataPoint =
db.Query<DataPoint>("SELECT * FROM DataPoint WHERE name = @name", new {name}).FirstOrDefault();
return dataPoint;
}
public T FormatObj<T>(T obj)
{
foreach (var propertyInfo in typeof(T).GetProperties())
{
var dataPoint = GetDataPoint(propertyInfo.Name);
//Do formatting on obj Properties such as setting values, etc...
}
return obj;
}
}
Explanation / Answer
You can use Memory Cache. I use memory cache to cache data rarely changes or at the specific time.
Here is example:
public static T GetCache<T>(string key, Func<T> initializer) where T : new() {
if (!MemoryCache.Default.Contains(key)) {
try {
T data = initializer();
AddData(key, data);
return (T)MemoryCache.Default[key];
} catch (Exception ex) {
LogHelper.WriteError(MethodBase.GetCurrentMethod(), ex);
return default(T);
}
}
return (T)MemoryCache.Default[key];
}
public static void AddData(string key, object data) {
if (data == null) {
return;
}
var cacheTime = int.Parse(ConfigurationManager.AppSettings["CachingExpiredTime"]);
AddData(key, data, cacheTime);
}
private static void AddData(string key, object data, int cacheMinute) {
if (data == null) {
return;
}
var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinute) };
MemoryCache.Default.Add(new CacheItem(key, data), policy);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.