C
C#16mo ago
Alizer

❔ How do I use a .cshtml (or Razor View) from a class library?

I wanted to make a modular ASP Core project, I wanted to make some kind of 'plugin system' for me project, basically some Razor views will be stored in class libraries, but currently I don't know how to do it, I followed the instruction at the Microsoft docs and Controllers work, I was able to add a controller class to my library and make it return a 200 OK on a specific route, however Razor views don't work, the following below is my code for importing .dll files
var pluginAssemblies =
Directory.GetFiles(Path.Combine(AppContext.BaseDirectory), "plugin/*.dll", SearchOption.AllDirectories);

// Load DLL plugins.
foreach (var pluginAssembly in pluginAssemblies)
{
try
{
var assemblyLoadContext = new AssemblyLoadContext(Path.GetFileName(pluginAssembly));
var assembly = assemblyLoadContext.LoadFromAssemblyPath(pluginAssembly);
var pluginTypes = assembly.GetTypes().Where(type => typeof(PluginBase).IsAssignableFrom(type));

foreach (var pluginType in pluginTypes)
{
builder.Services.AddScoped(typeof(IPlugin), pluginType);
builder.Services.AddControllersWithViews()
.AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();

builder.Services.Configure<MvcRazorRuntimeCompilationOptions>(o =>
{
o.FileProviders.Add(new EmbeddedFileProvider(pluginType.Assembly));
});

builder.Services.AddRazorPages().AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();
}
}
catch (Exception ex)
{
}
}
var pluginAssemblies =
Directory.GetFiles(Path.Combine(AppContext.BaseDirectory), "plugin/*.dll", SearchOption.AllDirectories);

// Load DLL plugins.
foreach (var pluginAssembly in pluginAssemblies)
{
try
{
var assemblyLoadContext = new AssemblyLoadContext(Path.GetFileName(pluginAssembly));
var assembly = assemblyLoadContext.LoadFromAssemblyPath(pluginAssembly);
var pluginTypes = assembly.GetTypes().Where(type => typeof(PluginBase).IsAssignableFrom(type));

foreach (var pluginType in pluginTypes)
{
builder.Services.AddScoped(typeof(IPlugin), pluginType);
builder.Services.AddControllersWithViews()
.AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();

builder.Services.Configure<MvcRazorRuntimeCompilationOptions>(o =>
{
o.FileProviders.Add(new EmbeddedFileProvider(pluginType.Assembly));
});

builder.Services.AddRazorPages().AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();
}
}
catch (Exception ex)
{
}
}
1 Reply
Accord
Accord16mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.