Blazor component 若需要使用 Service,可透過 DI 注入。
像是 Blazor 範本內就有一個 Service。
1 | using System; |
這個 Service 會在 Startup.ConfigureServices 這邊加入,指定為 Singleton 的 Service。
1 | public class Startup |
1 | using System; |
然後在 Blazor component 中透過 @inject directive 注進 Service。
1 | @inject WeatherForecastService ForecastService |
1 | @page "/fetchdata" |
運行後可看到 Blazor component 可以正常的從注入的 Service 取得資料做呈現。