使用编译时未知的ViewComponent

时间:2016-07-12 07:16:40

标签: .net asp.net-core-mvc .net-core

我正在开始一个新的ASP.Net MVC核心项目,我正在试图弄清楚如何做到以下几点:

我有一部分应用程序,我希望能够添加编译时未知的“插件”。我有一个页面,我想在其中添加一个“组件”,它可以来自外部源。

例如,我有一个包含基本信息的页面。假设我正在建造房屋销售软件。我有关于所有房屋相同的房屋的基本信息,但我有一个下拉列表,根据现有的插件和其他信息,在页面上显示编译时不一定知道的组件。

我看过ViewComponents,但看起来它们和Partial Views有点类似,使用InvokeAsync似乎意味着你必须在编译时知道它。

此外,您将如何存储这些ViewComponents的数据?

1 个答案:

答案 0 :(得分:3)

在编译时不需要知道视图组件。它们可以在运行时引用,但有一些技巧。首先,需要将类库中的cshtml文件作为嵌入资源包含在内。这可以通过将以下内容添加到类库的project.json中来完成:

"buildOptions": {
   "embed": "Views/**/*.cshtml"
}

在您的网络应用的Startup.ConfigureServices方法中,您需要向RazorViewEngineOptions添加嵌入式文件提供程序。这是为已知装配执行此操作的示例。

    //Get a reference to the assembly that contains the view components
var assembly = typeof(ViewComponentLibrary.ViewComponents.SimpleViewComponent).GetTypeInfo().Assembly;

//Create an EmbeddedFileProvider for that assembly
var embeddedFileProvider = new EmbeddedFileProvider(
    assembly,
    "ViewComponentLibrary"
);

//Add the file provider to the Razor view engine
services.Configure<RazorViewEngineOptions>(options =>
{                
    options.FileProviders.Add(embeddedFileProvider);
});

在您的情况下,您需要动态加载这些程序集,这可以使用AssemblyLoadContext.Default.LoadFromAssemblyPath为插件目录中的每个程序集完成。

var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);

很难回答如何在不了解应用程序和特定用例的情况下为视图组件存储数据的问题。

我已在此处的博客文章中概述了使用类库中的视图组件的过程:http://www.davepaquette.com/archive/2016/07/16/loading-view-components-from-a-class-library-in-asp-net-core.aspx

相关问题