Saturday, April 30, 2011

How to fix the “circular file references are not allowed” Error in ASP.Net


On one of my .Net projects, I came across an interesting issue.  I wasted couple of hours fixing it.  Hence, I decided to share my findings, so that others do not have to waste their time fixing the same issue. 

The issue

The issue was pretty simple, the app would not build.  The error that I was getting while building a ASP.Net web project using MSBuild was:

Of course the error said there is some sort of circular reference in my code.  I looked around to check and recheck, if I have created a circular reference by mistake.  However, if there was any circular reference, the code would not compile.  Code was compiling fine but it was failing when we ran aspnet_compiler.exe.


The ASP.Net Compilation tool (aspnet_compiler.exe) enables you to compile an ASP.Net Web application, this helps application performance because end users do not encounter a delay on the first request to the application.

I checked again, but certainly there was no code related circular dependency then why the aspnet_compiler.exe was complaining about the circular file references?

The Explanation

Googling a little, I found that, by default, in a Website Project, ASP.Net creates one DLL per folder. Hence, if you have the following setup:
  • User control ucA.ascx is present in the directory "A".  ucA.ascx refers another user control ucB.ascx
  • User control ucB.ascx is present in the directory "B".  ucB.ascx refers another user control ucC.ascx
  • User control ucC.ascx is present in the directory "A".
The folder A's DLL will reference the folder B's DLL, which will again reference the folder A's DLL, causing a "circular file reference".

This is the reason why the aspnet_compiler.exe fails with the "circular file reference" error.

The Fix

There are two ways this issue could be fixed
  • Rearrange the user controls (or MasterPages) to remove the circular references.  Usually this means moving the user controls in separate directories.  In our example, moving ucC.ascx to a new directory "C" (Preferred Solution).
  • Use batch=”false” in the compilation tag of the web.config file.  This will cause a new DLL to be created for each control/page in the site. This should fix the error but is really lousy for performance, so it should be avoided.
I moved the ucC.ascx in a different directory and yes the error went away!
Have some Fun!