views:

34

answers:

1

This seems to be the only thing that works:

  • If a .cs file is inside App_Code...
    • And does not contain extension methods: set the build action to "Compile"; otherwise no other source code in the project knows of its existence.
    • And contains extension methods: set the build action to "None"; otherwise you get an error that the reference to x.Foo is ambiguous between MyExtensions.Foo and MyExtensions.Foo.
  • If a .cs file is outside App_Code, inside a folder called Helpers, it must have build action set to "Compile," regardless of whether or not it contains extension methods.

I don't understand this behavior. I wasn't sure that ASP.NET MVC contained any special privileges for App_Code, but it looks like it does... but only in the sense that it auto-compiles extension-method containing .cs files, even when the build action is set to "None"?? Someone please explain.

A: 

I'm assuming you've created a Web Application Project, not a Web Site Project. The App_Code folder in an ASP.NET application is special. It is designed to allow you to drop in code to have it compiled with the website in place. Because of this, the project items are marked as "None" to make sure they are not compiled by Visual Studio. When you publish a Web Site Project to your hosted environment, the code files themselves are copied in the App_Code folder, and this is compiled into a seperate assembly by the ASP.NET runtime.

Now, when you create an MVC Web Application, you must remember that it is not the same project type as a Web Site Project. An MVC Web Application will compile locally to an assembly in your /bin directory. If you add an App_Code folder to your project with your code in and you change the Build type to Compile, you run into problems because:

  1. Your MVC application has compiled and includes a MyExtensions.Foo type and,
  2. ASP.NET is compiling the App_Code folder which also has a MyExtensions.Foo type.

My recommendation is to avoid using App_Code. I tend not to, as I favour a more concise project structure. Use the Models folder for code, or create other folders.....

If you really want to use an App_Code folder, it might be better to mark the build action of any of the files as "Content" to ensure they are copied to the output directory when publishing your site.

Matthew Abbott
This doesn't really explain why I have to set the build action to "Compile" for other, non extension-method source files. E.g. I defined a custom attribute that I used in various Models, and put the code for that attribute inside App_Code, but if I set the build action to "None" for that attribute's .cs file, then my project does not compile.
Domenic