From: TH on
> I'm not recompiling but sometimes it is done automatically when files
> are changed. Note that the object stored in the session has not been
> changed for ages.

If you are not pre-compiling your web application, any changes to the
web.config or files in the App_Code folder will trigger ASP.NET to re-compile
the web site, which often results in a new DLL being generated - and there
doesn't seem to be any mechanism for controlling this - other than to
pre-compile.

It doesn't matter if you haven't changed your object - the
AssemblyQualifiedName in the object's type has changed and so as far as the
..NET framework is concerned the types are incompatible.

//AssemblyQualifiedName = "MyObject, App_Code.5rwy5ukp, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null"
Session["123"] = new MyObject;

//Change to App_Code or web.config triggers a recompile into a new DLL -
App_Code.1frwq8gk

//This will throw an InvalidCastException because it is expecting an
AssemblyQualifiedName of "MyObject, App_Code.1frwq8gk, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null" but the object stored in session
belongs to a different assembly (App_Code.5rwy5ukp)
MyObject o = (MyObject)Session["123"];

//This will return NULL because the cast fails
MyObject o = Session["123"] as MyObject;

The best way to handle this scenario is to use the 'as' keyword and then
re-generate the object when a null is returned.

This ONLY affects custom objects - so you should store some kind of
'customer identifier' in a standard .NET type in session e.g. a string, and
when your custom object returns as null you can use the 'customer identifier'
to re-generate the object.

I believe the only other way around this, apart from pre-compiling, is to
use Reflection to copy the object from the old assembly into an object from
the new assembly. I believe the old assembly is still accessible as the old
DLL is still sitting in Temporary ASP.NET Files - so reflection should work.