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;
}
}
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);
}
2
I would say no. A singleton is rarely the answer. If you dont believe do a quick search on singleton anti pattern. The main problem being that it is hard to unit test code which uses a singleton.
A much more flexible approach is the inversion of control pattern. Basically you would would just make the class that would use your cache depend a IDataPoint instance in the constructor and then it is up the to calling point to decide how to create or reuse and which implementation of IDataPoint it wishes to provide.
1