rafalxyz
rafalxyz

Reputation: 169

Razor Runtime Compilation doesn't work with dynamically loaded assembly

I can't get Razor Runtime Compilation to work with a dynamically loaded assembly. My code:

Startup.cs

var assembly = Assembly.LoadFrom(someModuleDllPath);
var viewsAssembly = Assembly.LoadFrom(someModuleViewsDllPath);

services.AddControllersWithViews()
    .AddApplicationPart(assembly)
    .AddApplicationPart(viewsAssembly)
    .AddRazorRuntimeCompilation();
            
services.Configure<MvcRazorRuntimeCompilationOptions>(options => { 
    options.FileProviders.Add(new EmbeddedFileProvider(assembly)); 
});

With this approach, I need to rebuild the loaded assembly project and restart the host to see changes. When I replace the last two lines with:

services.Configure<MvcRazorRuntimeCompilationOptions>(options => {
    options.FileProviders.Add(new PhysicalFileProvider(loadedAssemblyProjectContentRootPath)); 
});

I get the error:

Cannot find compilation library location for package '<name of loaded assembly>'.

Setting MvcRazorExcludeRefAssembliesFromPublish to false doesn't change anything. The option with PhysicalFileProvider works when I add an explicit reference to the project.

I'm using .NET 5 and both projects have the Microsoft.NET.Sdk.Web type.

Is there any way I can make it work?

Upvotes: 4

Views: 701

Answers (1)

Jason Pan
Jason Pan

Reputation: 21838

Make sure the key of PreserveCompilationContext was set to false.

enter image description here

And you should use the path under the current project, that is, the relative path, such as the following code:

services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
{
    options.FileProviders.Add(new PhysicalFileProvider(Path.Combine(WebHostEnvironment.ContentRootPath, "..\\<name_of_loaded_assembly>")));
    options.AdditionalReferencePaths.Add(pluginAssembly.Location);
});

Upvotes: 3

Related Questions