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

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

问题描述

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

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天全站免登陆