Currently I have my VaryByCustom functionality implemented in classes that implement an interface IOutputCacheVaryByCustom
public interface IOutputCacheVaryByCustom
{
string CacheKey { get; }
HttpContext Context { get; }
}
A class implementing this interface has a few conventions the name of the class will be "OutputCacheVaryBy_______" where the blank is the value that is passed in from the varyByCustom property on pages. The other convention is that Context will be set through constructor injection.
Currently I'm basing this off an enum and a switch statement similar to
public override string GetVaryByCustomString(HttpContext context,
string varyByCustomTypeArg)
{
//for a POST request (postback) force to return back a non cached output
if (context.Request.RequestType.Equals("POST"))
{
return "post" + DateTime.Now.Ticks;
}
var varyByCustomType = EnumerationParser.Parse<VaryByCustomType?>
(varyByCustomTypeArg).GetValueOrDefault();
IOutputCacheVaryByCustom varyByCustom;
switch (varyByCustomType)
{
case VaryByCustomType.IsAuthenticated:
varyByCustom = new OutputCacheVaryByIsAuthenticated(context);
break;
case VaryByCustomType.Roles:
varyByCustom = new OutputCacheVaryByRoles(context);
break;
default:
throw new ArgumentOutOfRangeException("varyByCustomTypeArg");
}
return context.Request.Url.Scheme + varyByCustom.CacheKey;
}
Since I always know that the class will be OutputCacheVaryBy + varyByCustomTypeArg
and the only constructor argument will be context
I realized I could bypass needing this glorified if else block and could just instantiate my own object with Activator
.
With this being said, reflection is not my strong suit and I know that Activator
is substantially slow comparatively to static creation and other ways to generate objects. Is there any reason why I should stick with this current code or should I use Activator
or a similar way to create my object?
I've seen the blog http://www.smelser.net/blog/post/2010/03/05/When-Activator-is-just-to-slow.aspx but I'm not really sure how this would apply since I'm working with types at runtime not static T.