dotnet / dotnet/aspnetcore

Reduce boilerplate when enabling runtime compilation for a Razor Class Library

Open
#36,006 3 comments 0 reactions 0 assignees View on GitHub
api-suggestion area-mvc enhancement
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

## Background and Motivation

You need to write this boilerplate if you need to [enable runtime compilation for a razor class library](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-compilation?view=aspnetcore-5.0&tabs=visual-studio#enable-runtime-compilation-for-a-razor-class-library-1):

```cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages()
.AddRazorRuntimeCompilation();

services.AddSingleton, ConfigureRazorRuntimeCompilation>();
}

private class ConfigureRazorRuntimeCompilation : IConfigureOptions
{
private readonly IHostEnvironment _env;

public ConfigureRazorRuntimeCompilation(IHostEnvironment env)
{
_env = env;
}

public void Configure(MvcRazorRuntimeCompilationOptions options)
{
var path = Path.Combine(_env.ContentRootPath, "..", "MyRazorClassLibrary");
var provider = new PhysicalFileProvider(Path.GetFullPath(path));

options.FileProviders.Add(provider);
}
}
```

See this GitHub search to see folks using this pattern: https://github.com/search?q=IConfigureOptions+MvcRazorRuntimeCompilationOptions&type=code

## Proposed API

```diff
namespace Microsoft.Extensions.DependencyInjection
{
public static class RazorRuntimeCompilationMvcBuilderExtensions
{
public static IMvcBuilder AddRazorRuntimeCompilation(this IMvcBuilder builder, Action setupAction);

+ public static IMvcBuilder AddRazorRuntimeCompilation(this IMvcBuilder builder, Action setupAction);
}
}
```

## Usage Examples

```cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages()
.AddRazorRuntimeCompilation((options, env) =>
{
var path = Path.Combine(_env.ContentRootPath, "..", "MyRazorClassLibrary");
var provider = new PhysicalFileProvider(Path.GetFullPath(path));

options.FileProviders.Add(provider);
});
}
```

## Alternative Designs

N/A

## Risks

N/A

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.