I have an array that stores a type dictionary:
I would like to use this Dictionary to declare a variable of type T
//instead of T myvar; //I want to dynamically declare myvar as: //1)get the type for the cacheKey from the dictionary: Type type = TypeLookup[cacheKey]; //2)declare myvar as the corresponding Type: type myvar;
It is assumed that I am creating a distributed caching infrastructure. I have a very small CachingProvider that allows you to update an item in the cache.
I would like to open this method as a web service so that all servers in my farm can update their cache. But I would like to have only one method open as a web service, which then updates the corresponding item in the cache.
This is the method I'm trying to open:
public static void UpdateCacheEntryItem<T>(CacheKey cacheKey, int id) {
Things I tried: 1) I tried to expose the method directly as a WCF service, but of course this does not work due to the method. 2) I tried pouring the Dictionary, which will be found, because I do not need to do anything with the return value, I just need to update the item in the cache. But that didn't work either. The error I get: cannot list an object of type 'System.Collections.Generic.Dictionary 2[System.Int32,CachingPrototype.CustomerQuickSearch]' to type 'System.Collections.Generic.Dictionary 2 [System.Int32, System.Object] '.
Your comments were very helpful and helped me answer my question. The solution I came up with is simply to include my WCF method in the switch statement so that I can call the UpdateCacheEntryItem method with the correct type T. Since there is no way to convert from Type to a general T operator, this is the only option. Since I don't have many types in the cache, this works very well. (Another solution would be to use an interface as indicated below, but that would not be as strong as we would like.)
[OperationContract] public void UpdateCacheEntryItem(CacheKey cacheKey, int id) { switch (cacheKey) { case CacheKey.UserProfile: CacheProvider.UpdateCacheEntryItem<UserProfile>(cacheKey, id); break; case CacheKey.CommissionConfig: CacheProvider.UpdateCacheEntryItem<CommissionConfig>(cacheKey, id); break; case CacheKey.CustomerQuickSearch: CacheProvider.UpdateCacheEntryItem<CustomerQuickSearch>(cacheKey, id); break; default: throw new Exception("Invalid CacheKey"); }
Thank you all for your help, you are great!