How can we get compile time errors in views and view components in Mvc6?
In MVC 5, it was simple to edit the .csproj
file. How do we do it now?
RazorPreCompilation
class:namespace YourApp.Compiler.Preprocess
{
public sealed class RazorPreCompilation : RazorPreCompileModule
{
protected override bool EnablePreCompilation(BeforeCompileContext context) => true;
}
}
AddPrecompiledRazorViews
in your ConfigureServices
method.public void ConfigureServices(IServiceCollection services)
{
// ... other code ...
services
.AddMvc()
.AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
// ... other code ...
}
As noted in other answers, when views are precompiled you lose the ability to change them while the application is running. Additionally, it seems that sometimes you have to do a rebuild on your project (as opposed to just a build) in order for new code changes to take effect. For example, correcting a typo in a Razor method call may still trigger a compilation error until you rebuild the project.
If you'd like to have this run with preprocess directives, wrap them around the AddPrecompiledRazorViews
call like this:
public void ConfigureServices(IServiceCollection services)
{
// ... other code ...
var mvcBuilder = services.AddMvc()
#if !DEBUG
mvcBuilder.AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
#endif
// ... other code ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With