![](/img/trans.png)
[英]ASP.NET Core MVC main project can't reach Controllers in separate assembly
[英]How to separate asp.net core mvc project into multiple assembly (.dll)?
如何將asp.net核心mvc項目分成多個程序集(.dll)?
我有3個項目
HR項目
ACC項目
我想編譯成dll
我想將這些dll(HR.dll,HR.Views.dll,ACC.dll,ACC.Views.dll)的引用添加到MyApp Project中。
然后運行MyApp項目也可以訪問Employee&Chart Account模塊。
如果你想這樣做,你需要做以下兩個步驟:
stackoverflow上已有解決方案: 如何在ASP.NET Core MVC 2.0中的另一個程序集中使用控制器?
它說如下:
在
Startup
類的ConfigureServices
方法中,您必須調用以下內容:services.AddMvc().AddApplicationPart(assembly).AddControllersAsServices();
stackoverflow上還有一個解決方案:
如何使用CompiledRazorAssemblyPart加載Razor視圖?
這是上面鏈接中的一種可能的解決方案:
你需要做的是:
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) { } } }
如果你在我們單獨的MVC項目中也有javascript和css文件,你需要將它嵌入你的dll,否則你的主應用程序將看不到它。 因此,在您的HR和ACC項目中,您需要在.csproj文件中添加它:
<ItemGroup>
<EmbeddedResource Include="wwwroot\**" />
</ItemGroup>
而且要明確,我同意其他評論,我認為它不是一個好的架構,但如果你願意,它可以做到。
只需一步:
在ConfigureServices方法中編輯Startup.cs
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApplicationPartManager(ConfigureApplicationParts);
和方法:
private void ConfigureApplicationParts(ApplicationPartManager apm)
{
var rootPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var assemblyFiles = Directory.GetFiles(rootPath , "*.dll");
foreach (var assemblyFile in assemblyFiles)
{
try
{
var assembly = Assembly.LoadFile(assemblyFile);
if (assemblyFile.EndsWith(this.GetType().Namespace + ".Views.dll") || assemblyFile.EndsWith(this.GetType().Namespace + ".dll"))
continue;
else if (assemblyFile.EndsWith(".Views.dll"))
apm.ApplicationParts.Add(new CompiledRazorAssemblyPart(assembly));
else
apm.ApplicationParts.Add(new AssemblyPart(assembly));
}
catch (Exception e) { }
}
}
你想要的是不可能的,或者更好的說法:肯定不是一個好主意。
通常,您需要使用Razor類庫。 然后,所有常見功能將進入那些RCL。 您的整個HR和ACC項目可能是RCL,除非您需要獨立運行這些項目,作為完整的Web應用程序。 在這種情況下,您需要一個更像是的結構:
在任何一種情況下,您都需要在RCL中共享所有需要共享的控制器,視圖和靜態資源,因此,如果您確實擁有實際的HR / ACC Web應用程序,那么這些應用程序非常簡單:大多數只包含Program
和Startup
和依賴於各自的RCL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.