Ramblings

ASP.NET Core MVC Faster View Compiling!

By November 15, 2019 No Comments

In previous versions of ASP.NET you could make changes to a .cshtml view file and the changes would automatically be reflected by just refreshing the browser. As of the latest dotnet core build, v3.0, this feature was missing. There is an additional library that you can bring into your project that will re-enable this power.

Run the following command to add the Razor Runtime compilation library to the project.

dotnet add package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

Then you can add the runtime compilation step into the Startup ConfigureServices middleware. This will allow you to make changes to your views without having to restart the project.

services.AddControllersWithViews().AddRazorRuntimeCompilation();

Lastly, you can check the development environment with an if block (because you won’t need this runtime building power in production). You can inject the IHostEnvironment into the Startup constructor and check for the environment within the ConfigureServices method as noted below.

public Startup(IConfiguration configuration, Microsoft.Extensions.Hosting.IHostEnvironment environment)
{
    Configuration = configuration;
    Environment = environment;
}

public IConfiguration Configuration { get; }
public IHostEnvironment Environment { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    if (Environment.IsDevelopment())
    {
        services.AddControllersWithViews().AddRazorRuntimeCompilation();
    }
    else
    {
        services.AddControllersWithViews();
    }
}