5

See, I am developing a website as a MVC4 project. This site often queries its database for various settings in a very simple way:

private static T GetSetting<T>(string parameterName)
{
    return (T)Convert.ChangeType(/* bla bla SQL query code */, typeof(T));
}

The logical question will be - what the heck, are you quering the database each time you want to get any setting? And what if you need it in some for cycles or stuff?

So I come up with the caching solution and I need to know if i did the best I could. What do you think?

internal static void ClearCache()
{
    foreach (IDictionary cache in _caches)
        cache.Clear();
}
private static readonly HashSet<IDictionary> _caches = new HashSet<IDictionary>();
private static class TypedCache<T>
{
    private static readonly Dictionary<string, T> _cache = new Dictionary<string, T>();
    internal static Dictionary<string, T> Cache { get { return _cache; } }
}

private static T GetSetting<T>(string parameterName)
{
    T value;

    if (!TypedCache<T>.Cache.TryGetValue(parameterName, out value))
    {
        _caches.Add(TypedCache<T>.Cache);
        TypedCache<T>.Cache[parameterName] = value =
            (T)Convert.ChangeType(/* bla bla SQL query code */, typeof(T));
    }

    return value;
}

I heard the IIS can create more than one copy of my DLL in the memory (by using multiple IIS processes). How by the way I can force him to use only one? Because of that the whole my idea can go to hell.

Surfbutler
  • 1,529
  • 2
  • 17
  • 38
AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • 1
    Why not just use `System.Web.Caching`? http://msdn.microsoft.com/en-us/library/system.web.caching.aspx – Jodrell Aug 02 '12 at 07:59
  • @Jordell I just do not know how to. – AgentFire Aug 02 '12 at 08:07
  • Why not use [`System.Web.Caching`](http://msdn.microsoft.com/en-us/library/system.web.caching.aspx) in the way described in this [answer](https://stackoverflow.com/a/349111/659190). – Jodrell Aug 02 '12 at 08:08

1 Answers1

0

You should only use Convert when you want to change the type of a value, eg. converting a string to a number or vice-versa. In your case the values already have the correct types (I assume) so you just need to cast.

You don't need a separate dictionary per type, this doesn't buy you anything. Just use a single Dictionary<string, object>, and cast (not Convert) to T in GetSetting<T>.

JacquesB
  • 41,662
  • 13
  • 71
  • 86