views:

385

answers:

3

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.

+2  A: 

I don't think this is possible. StackTrace and StackFrame just give you metadata information about who called your method, not the actual instance like you need.

Matt Dearing
+1  A: 

This is not possible. The way arguments are passed to a method is an implementation detail, left to the JIT compiler. It is very different between x86 and x64 for example. x86 passes arguments on the stack, x64 passes the first 4 arguments through registers. Floating point values are passed either on the FPU stack or SSE register. Etcetera.

The debugger is aware of the details by using debugging info generated by the JIT compiler. But using the debugging interfaces in a program can't work, programs cannot debug themselves.

Hans Passant
Very good info. Thanks so much!
John
+1  A: 

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?

luckyluke
I was definately over thinking it. Thanks, that was exactly what I needed.
John