gpt4 book ai didi

c# - 插件中的 ASP .NET Core MVC 2.1 mvc View

转载 作者:行者123 更新时间:2023-11-30 12:20:15 34 4
gpt4 key购买 nike

有个问题困扰了我好几天。

就像我在 ASP .NET Core MVC 的插件中所做的那样,通过插件给我带来 View

我有这种情况

解决方案:EVS

  • Controller
    • ...
  • 观点
    • ...
  • 插件
    • 这个文件夹包含一个插件dll
  • 其他文件夹...
  • IPlugin.cs
  • 程序.cs
  • Startup.cs

文件IPlugin.cs

...
using McMaster.NETCore.Plugins;

namespace EVS
{
public interface IPlugin
{
string Name { get; }
void Do();
void BootReg();
void BootExecute();
void PluginConfigure(IApplicationBuilder app, IHostingEnvironment env);
void PluginConfigureServices(IServiceCollection services);
}

public class PluginsManager
{
public List<PluginLoader> PluginLoaders;

public Dictionary<string, IPlugin> Plugins;
public Dictionary<string, Assembly> Views;
public List<String> dllFileNames;

public PluginsManager()
{
PluginLoaders = new List<PluginLoader>();
Plugins = new Dictionary<string, IPlugin>();
dllFileNames = new List<string>();
string PloginDirectory= Path.Combine(AppContext.BaseDirectory, "Plugins");
if (Directory.Exists(PloginDirectory))
dllFileNames.AddRange(Directory.GetFiles(PloginDirectory+"\\", "*.dll"));

foreach (string dllFile in dllFileNames)
{
if (!dllFile.Contains(".Views.dll"))
{
var loader = PluginLoader.CreateFromAssemblyFile(dllFile,sharedTypes: new[] { typeof(IPlugin) });
PluginLoaders.Add(loader);
}
else
{
//

//
}
}
foreach (var loader in PluginLoaders)
{
foreach (IPlugin plugin in loader.LoadDefaultAssembly().GetTypes().Where(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsAbstract).Select((x)=> (IPlugin)Activator.CreateInstance(x)))
if (!Plugins.ContainsKey(plugin.Name))
Plugins.Add(plugin.Name, plugin);
}
}
}
}

文件程序.cs

namespace EVS
{
public class Program
{
public static void Main(string[] args)
{
foreach (IPlugin plugin in Global.Static.PluginsManager.Plugins.Select((x) => x.Value))
plugin.BootReg();

CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}

文件 Startup.cs

namespace EVS
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});


services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

foreach (IPlugin plugin in Global.Static.PluginsManager.Plugins.Select((x) => x.Value))
{
plugin.PluginConfigureServices(services);
}
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();
app.UseCookiePolicy();

foreach (IPlugin plugin in Global.Static.PluginsManager.Plugins.Select((x) => x.Value))
{
plugin.PluginConfigure(app,env);
}

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}

现在让我们以插件为例

解决方案:EVS.TestPlugin

  • Controller
    • TestPluginController.cs
  • 观点
    • test.cshtml
  • 测试插件.cs

文件:TestPlugin.cs

namespace EVS.TestPlugin
{
internal class TestPlugin : IPlugin
{
public string Name
{
get
{
return "TestPlugin";
}
}

public void BootReg()
{
...
}

public void BootExecute()
{
...
}

public void Do()
{

}


public void PluginConfigure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc(routes =>
{
routes.MapRoute("TestPlugin", "TestPlugin/", new { controller = "TestPlugin", action = "index" });
routes.MapRoute("TestPlugint1", "TestPlugin/t1", new { controller = "TestPlugin", action = "t1" });
});
}

public void PluginConfigureServices(IServiceCollection services)
{

services.AddMvc().AddApplicationPart(typeof(TestPluginController).GetTypeInfo().Assembly).AddControllersAsServices();
}

}
}

文件:Controllers/TestPluginController.cs

namespace EVS.TestPlugin.Controllers
{
public class TestPluginController : Controller
{
public IActionResult Index()
{
return Content("<h1>TestPluginController</h1>");
}

public IActionResult t1()
{
return View("test");
}
}
}

文件:Views/test.cshtml

@{
Layout = null;
}

`.cshtml` test view

插件不包含在解决方案中,但它们会动态加载,具体取决于它们是否位于为它们郑重其事的文件夹中。

问题:我可以相应地添加 Controller 作为 (EVS.TestPlugin.PluginConfigureServices (...))MapRoute (EVS.TestPlugin.PluginConfigure (...))但是,我怎样才能添加 View 的上下文呢? 因此它将是: ~/PluginName/Views/ViewName.cshatml

编辑

我找到了这个 ( link ),但这并不是我真正需要的。它部分解决了问题,因为它只有在编译 View 时才有效。

编辑 2

暂时我解决了它,将 View 引用添加到插件 csproj,如下所示:

<ItemGroup>
<EmbeddedResource Include="Views\**\*.cshtml"/>
<Content Remove="Views\**\*.cshtml" />
</ItemGroup>
<PropertyGroup>
<RazorCompileOnBuild>false</RazorCompileOnBuild>
</PropertyGroup>

在源项目上:

// p is a Instance of plugin
foreach(IPlugin p in Plugins.Select((x) => x.Value))
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(
new EmbeddedFileProvider(p.GetType().GetTypeInfo().Assembly));
});

这不能解决我的问题,因为 .cshtml插件文件中的文件很清楚,我需要的是能够从程序集添加 View pluginname.views.dll或者以其他方式,编译 View 很重要

编辑 3

好消息,我使用 ILSpy 解析了一个 PluginName.Views.dll文件,我发现它实现了 RazorPage<object>

使用以下代码,我验证了我可以初始化 cono RazorPage<object> 的所有缓存。这允许我拥有创建 View 的对象的实例

foreach (string dllview in Views.Select((x) => x.Key))
{
PluginLoader loader = PluginLoader.CreateFromAssemblyFile(dllview, sharedTypes: new[] { typeof(RazorPage<object>) });
foreach (RazorPage<object> RazorP in loader.LoadDefaultAssembly().GetTypes().Where(t => typeof(RazorPage<object>).IsAssignableFrom(t)).Select((x) => (RazorPage<object>)Activator.CreateInstance(x)))
{
// i need a code for add a RazorPagein the in RazorViewEngine, or anywhere else that allows register in the context

System.Diagnostics.Debug.WriteLine(RazorP.GetType().ToString());
/* - output
AspNetCore.Views_test
AspNetCore.Views_TestFolder_htmlpage

as you can see is the folder structure

- folder tree:
Project plugin folder
Views
test.cshtml
TestFolder
htmlpage.cshtml

*/
}
}

已解决

感谢我解决的所有问题,似乎有问题

var assembly = ...;
services.AddMvc()
.AddApplicationPart(assembly)

有人连 Razor 配件厂都忘了

CompiledRazorAssemblyApplicationPartFactory

我解决了

services.AddMvc().ConfigureApplicationPartManager(apm =>
{
foreach (var b in new CompiledRazorAssemblyApplicationPartFactory().GetApplicationParts(AssemblyLoadContext.Default.LoadFromAssemblyPath(".../ViewAssembypath/file.Views.dll")))
apm.ApplicationParts.Add(b);
});

此外,我还发布了一个可以高效完成所有工作的库

NETCore.Mvc.PluginsManager

最佳答案

感谢我解决的所有问题,似乎有问题

var assembly = ...;
services.AddMvc()
.AddApplicationPart(assembly)

有人连 Razor 配件厂都忘了

CompiledRazorAssemblyApplicationPartFactory

我解决了

services.AddMvc().ConfigureApplicationPartManager(apm =>
{
foreach (var b in new CompiledRazorAssemblyApplicationPartFactory().GetApplicationParts(AssemblyLoadContext.Default.LoadFromAssemblyPath(".../ViewAssembypath/file.Views.dll")))
apm.ApplicationParts.Add(b);
});

此外,我还发布了一个可以高效完成所有工作的库

NETCore.Mvc.PluginsManager

关于c# - 插件中的 ASP .NET Core MVC 2.1 mvc View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52722484/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com