The short answer is that you can't prevent it from running, and that this is by design but you can workaround the problem.
Why PreApplicationStart methods run during aspnet_compiler.exe
The reason is that PreApplicationStartMethod
(or WebActivator, which builds on top of it) can be used for things that actually affect compilation, such that if you omitted it the site may not compile.
To give you an example, you can add namespaces to the compilation in a PreAppStart
method, which then affects compilation of your Razor pages.
Obviously, not every PreAppStart
method needs to run when you use aspnet_precompiler, but we do run all of them in case they are needed.
Detecting whether you're running under aspnet_compiler.exe
If the code in there breaks under aspnet_compiler, it may be necessary to add conditional logic in the PreAppStart
method to detect the situation and omit running the code.
You can look at System.Web.Hosting.HostingEnvironment.InClientBuildManager
propery to determine whether your PreAppStart
method is running under the context of aspnet_compiler.exe (where it will be true
), or at runtime (where it will be false
). InClientBuildManager
also applies to building a web site within VS, which uses basically the same code path as aspnet_compiler.exe.
Try using PostStart methods instead
Note that WebActivator also supports PostApplicationStartMethod
, and those will not run under aspnet_compiler. That code runs after Application_Start
, so it may or may not be appropriate to your scenario. But it may be a solution for you.
aspnet_compiler.exe Debugging tip
Not directly related but useful for debugging: you can pass -errorstack to aspnet_compiler.exe to get a more complete stack when there is an error.
PreApplicationStart
, or would it be acceptable to move the code you have in there somewhere else? – Moncton