Dynamic Compilation in a Web Application

,

With a simple trick, you can mimic the dynamic complilation of a Web Site in a Web Application.

Visual Studio 2008 comes with the Web Application project type build-in. As you may know, the main difference between a Web Application and a Web Site is that a Web Application must be compiled, whereas a Web Site uses dynamical compilation, where the page is compiled when a user first reach it. The compiled code is stored in the frameworks Temporary ASP.NET Files folder, until the codebehind is changed.

Hence the normal way to use a Web Site is simply to copy the mark-up and the codebehind to some webserver, and let the user do the compilling. But a Web Site can be precompiled: One way to do this is to use Visual Studios Publish function, where the Web Site is compiled to some destination, with the compiled code is stored in the Bin folder. You can choose to compiled the codebehind or the codebehind and the markup by selecting Precompile for Deployment or Precompile for Deployment and Update.

But my problem is the other way around: I often work on Sitecore projects, which are normally Web Applications. I must say, that while I generally prefer this project type, it can a pain when e.g. developing User Controls. This normally means that I have to recompile alot, but I found on that if I change the CodeBehind attibute in the Control directive, I could force the User Control to use dynamic complition.The same goes with pages by the way.

The codebehind is wired to the mark-up by a directive within the mark-up. For a control, it goes something like:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SomeFile.ascx.cs" Inherits="SomeClass" %>

So by changing this to

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SomeFile.ascx.cs" Inherits="SomeClass" %>

I can make SomeFile.ascx.cs dynamically compile upon changes. So how does it behave? I tried using two User Controls on the same page, the one using CodeBehind and the other using CodeFile, and it worked as expected: The CodeFile control dynamically compiled whereas the CodeBehind control used the compiled code from the dll. Now, except from the above, the two controls where actually identical, so I thought: What will happen if I inherits the same codebehind, but with CodeBehind in the first control and CodeFile in the second … they both used the dynamically compiled code, dropping the code in the dll all together.

I regard this as a kind of a hack, and I always change the references back to CodeBehind and compile the project before deploying. But for developing, it saves me a lot of compiling.

One response to “Dynamic Compilation in a Web Application”

  1. Ben Hart Avatar

    Interesting. Thanks!