加载 Razor Class 库作为插件
Loading Razor Class Libraries as plugins
当使用带有 ASP.net 核心 2.1 的 Razor Class 库时,如果我添加对 class 库的引用,它会按预期加载控制器和视图。
但问题是,如何在运行时动态加载这些模块?
我想将模块放在设计时未引用的目录中,并在应用程序启动时加载它们。
我尝试使用应用程序部件。但是那样的话,控制器会被加载,但视图不会被发现。
我完全忘记了 CompiledRazorAssemblyPart。
我们需要做的是:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.ConfigureApplicationPartManager(ConfigureApplicationParts);
并像这样配置部件
private void ConfigureApplicationParts(ApplicationPartManager apm)
{
var rootPath = HostingEnvironment.ContentRootPath;
var pluginsPath = Path.Combine(rootPath, "Plugins");
var assemblyFiles = Directory.GetFiles(pluginsPath, "*.dll", SearchOption.AllDirectories);
foreach (var assemblyFile in assemblyFiles)
{
try
{
var assembly = Assembly.LoadFile(assemblyFile);
if (assemblyFile.EndsWith(".Views.dll"))
apm.ApplicationParts.Add(new CompiledRazorAssemblyPart(assembly));
else
apm.ApplicationParts.Add(new AssemblyPart(assembly));
}
catch (Exception e) { }
}
}
当使用带有 ASP.net 核心 2.1 的 Razor Class 库时,如果我添加对 class 库的引用,它会按预期加载控制器和视图。 但问题是,如何在运行时动态加载这些模块? 我想将模块放在设计时未引用的目录中,并在应用程序启动时加载它们。 我尝试使用应用程序部件。但是那样的话,控制器会被加载,但视图不会被发现。
我完全忘记了 CompiledRazorAssemblyPart。
我们需要做的是:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.ConfigureApplicationPartManager(ConfigureApplicationParts);
并像这样配置部件
private void ConfigureApplicationParts(ApplicationPartManager apm)
{
var rootPath = HostingEnvironment.ContentRootPath;
var pluginsPath = Path.Combine(rootPath, "Plugins");
var assemblyFiles = Directory.GetFiles(pluginsPath, "*.dll", SearchOption.AllDirectories);
foreach (var assemblyFile in assemblyFiles)
{
try
{
var assembly = Assembly.LoadFile(assemblyFile);
if (assemblyFile.EndsWith(".Views.dll"))
apm.ApplicationParts.Add(new CompiledRazorAssemblyPart(assembly));
else
apm.ApplicationParts.Add(new AssemblyPart(assembly));
}
catch (Exception e) { }
}
}