Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 843
rafalxyz Avatar asked Sep 12 '25 05:09

rafalxyz


1 Answers

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);
});
like image 81
Jason Pan Avatar answered Sep 14 '25 19:09

Jason Pan