The Dual Life of Code Behind

When you create an ASP.NET page using Visual Studio .NET, the default processing model is to use code-behind (the basics of which I described here). One of the more interesting aspects of code-behind is that you can specify the code for the code-behind assembly using two different techniques.  The first, and most commonly used is to build an assembly and deploy it to the bin directory on the web server.  The second mechanism is to specify the file containing the source code in the Page directive for the ASPX file.

Compiled Assembly

<%@ Page Language=”C#” Inherits=”ObjectSharp.WebPageClass” %>

Source Code

<%@ Page Language=”C#” Src=”WebPageClass.cs” %>

There are pros and cons to both of these approaches.  Functionally, they are equivalent.  When the first request is made to the page, the source code file is compiled and the resulting assembly loaded into memory. For every subsequent request, no compilation is required. Not only does this mean functional equivalence, but it also means that there is no performance penalty for deploying source code instead of a compiled assembly.

The biggest downside of the source code technique is exactly that, however.  That the code file needs to be deployed onto the web server.  This, naturally, has the potential to be a security problem.  A deployed assembly doesn’t have quite the same exposure, if only because it can be deployed into the Global Assembly Cache instead of directly into the application’s virtual server.

While it might seem that the security risk might tilt the tables entirely towards compiled assemblies, that isn’t true.  The problem with compiled assemblies has to do with updates to the web site.  When a new version of a compiled assembly is deployed to the web server, IIS is smart enough to detect the change.  The current web application is stopped and restarted so that the modified assembly can be loaded.  Unfortunately, the stopping and starting of the web application means that every Application and, more importantly, Session variable is discarded.  Depending on how the web application has been designed, this can be a significant problem.

Source code deployment doesn’t suffer from the same problem.  As with compiled assemblies, IIS monitors the source code files, so that when an update occurs, a recompilation takes place.  So the updates do get activated immediately.  The difference is that the web application does not have to be stopped and started in order to get the changes in place.

Choices, choices.  The trick to ASP.NET, as it is with almost any discipline, is to understand not only the choices but when each can and should be used.  This not only helps you design better web applications, but also solve those nagging times when the web application seems to restart for no apparent reason.