I’m making pretty heavy use of reflection in my current project to greatly simplify communication between my controllers and the wcf services. What I want to do now is to obtain a value from the Session within an object that has no direct access to HttpSessionStateBase (IE: Not a controller). For example, a ViewModel. I could pass it in or pass a reference to it etc. but that is not optimal in my situation.
Since everything comes from a Controller at some point in my scenario I can do the following to walk the sack to the controller where the call originated, pretty simple stuff:
var trace = new System.Diagnostics.StackTrace();
foreach (var frame in trace.GetFrames())
{
var type = frame.GetMethod().DeclaringType;
var prop = type.GetProperty("Session");
if(prop != null)
{
// not sure about this part...
var value = prop.GetValue(type, null);
break;
}
}
The trouble here is that I can’t seem to work out how to get the “instance” of the controller or the Session property so that I can read from it.
Why can’t You use HttpContext.Current.Session? You don’t want a reference to the Web part? Otherwise I think You will need an interface – session facade set up somewhere (which is useful always) – a singleton is useful or maybe set it up using a container like unity.
The httpContext is thread aware and it serves sesion quite nice. You can make an abstraction on the session by providing the facade I said before to make it more provider agnostic, but still using debug infrastructure in production code is… questionable.:)
Maybe you can use IL generation in some sense if You don’t want the coupling?