加载 Razor 类库作为插件 [英] Loading Razor Class Libraries as plugins

查看:33
本文介绍了加载 Razor 类库作为插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ASP.net core 2.1 中使用 Razor 类库时,如果我添加对类库的引用,它会按预期加载控制器和视图.但问题是,如何在运行时动态加载这些模块?我想将模块放在设计时未引用的目录中,并在应用程序启动时加载它们.我尝试使用应用程序部件.但是那样,控制器会被加载,但视图不会被发现.

When using Razor Class Libraries with ASP.net core 2.1, if I add reference to the class library, it loads controllers, and views as expected. But the question is, how can I load this modules dynamically at runtime? I want to put modules at directory, which are not referenced at design time, and load them at the start up of the app. I tried to use Application Parts. But that way, controllers are loaded, but views are not discovered.

推荐答案

我完全忘记了 CompiledRazorAssemblyPart.

I had completely forgot about 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) { }
        }
    }

这篇关于加载 Razor 类库作为插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆