使用ASP.NET CORE開發可載入套件的基礎架構(2)

Likol Lee
Likol Lee
Nov 4 · 3 min read

前言

有了組件的基礎載入機制後,首要解決的問題便是"如何讓套件可以載入自訂的服務或功能?",並且也必須可以在開發階段進行偵錯,而且還需要解決以下的問題:

  1. Startup (Development)
  2. ConfigServices與Configure
  3. wwwroot 靜態內容
  4. Library、RazorPage(包含View)、Controller、TagHelper, ViewComponent (使用ApplicationPartManager即可)

Startup (Development)

ASP.NET CORE依賴Startup.cs來進行網站功能的設定,但是我並不希望每一個套件開發專案都存在重複的Startup檔案,這樣會造成難以維護管理。

查了相關的文件後發現有一個名為HostingStartupAttribute的類別,可以用來指定使用目前組件啟動網站時額外的Startup內容。這樣就可以在公用的專案中先配置好Startup的內容,而套件的開發專案只要引用即可。

ConfigureServices與Configure

每個組件需要自行增加的服務或功能,必須定義在各自的組件(Assembly)中,因此我增加了一個PackageStartupAttribute來作為依據。

當每一個組件被載入時,可以透過Assembly.GetCustomAttribute取得是否含有此屬性,如果有則使用Activator.CreateInstance建立對應物件,並執行對應的功能。

wwwroot 靜態內容

每個套件都有可能有自己需要的JS與CSS檔案,透過在專案中加入GenerateEmbeddedFilesManifest的屬性,可以將專案項目設定為EmbeddedResource的檔案包裝至組件中。

同樣的我增加了一個EmbeddedWebRootFileAttribute來作為組件中是否含有靜態內容的依據,當組件被載入時如果組件存在這個屬性,則表示需要載入靜態內容。

載入的動作則是要透過StaticFileOptions,建立新的ManifestEmbeddedFileProvider並新增至FileProvider中。

[延伸閱讀]

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade