iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
自我挑戰組

ASP.NET Core & Blazor系列 第 5

Day 05 依賴注入(Dependency Injection)

  • 分享至 

  • twitterImage
  •  

問題來了,為什麼Blazor會知道WeatherForecastService在這裡可以調用?

day03有提到Startup.cs的ConfigureServices的目的就是「設定服務」,Controller把資料回傳這件事情就是一種服務,我們點開Startup.cs,可以在ConfigureServices找到一行程式
services.AddSingleton<WeatherForecastService>();
把這行字拿掉,重整網頁,可以看到這樣的錯誤訊息,因為我們試圖在FetchData.razor調用WeatherForecastService,卻沒告訴Blazor我們要註冊這個服務。
https://ithelp.ithome.com.tw/upload/images/20210905/20140893202kmuR48k.png

不過這並不是day03說到的依賴注入,依賴注入的目的是擺脫高層級程式必須相依於低層級程式的窘境,以減少耦合性。舉例來說,如果今天FetchData.razor要呼叫其他Service例如NewWeatherForecastService的同名方法GetForecastAsync,取回10筆資料,那只要用到WeatherForecastService的地方都必須修改,目前因為範例的關係不多所以沒感覺,如果日後有10幾20幾個地方要改呢?

這時候就是依賴注入發揮功能的時候了,先定義一個介面
interface IWeatherForecastService
https://ithelp.ithome.com.tw/upload/images/20210905/20140893OTiMRaOODz.png
裡面就寫我們要的方法
Task<WeatherForecast[]> GetForecastAsync(DateTime startDate);
也不用實作(雖然介面也不能實作),接著讓WeatherForecastServiceNewWeatherForecastService繼承IWeatherForecastService
https://ithelp.ithome.com.tw/upload/images/20210905/20140893R4JSv3eJvj.pnghttps://ithelp.ithome.com.tw/upload/images/20210905/20140893RQt3xlDeB4.png
Startup.cs改用IWeatherForecastServiceNewWeatherForecastService註冊
https://ithelp.ithome.com.tw/upload/images/20210905/20140893MA170iZMeK.png
最後在FetchData.razor改為注入IWeatherForecastService
https://ithelp.ithome.com.tw/upload/images/20210905/20140893kcJtqgFfWX.png
重整網頁就能看到資料筆數變為10筆了
https://ithelp.ithome.com.tw/upload/images/20210905/20140893N67RI9K4UE.png

依賴注入的核心觀念就是「對某個功能的依賴性是透過注入的方式」,不直接呼叫底層程式,而是呼叫底層程式的介面,即便底層程式更動也不會導致所有呼叫該程式的呼叫端都必須改動。

註:由於筆者是在寫完這篇之後才想起來生命週期,原本想用git rebase的功能回到這一次的commit新增範例,但會有git斷頭疑慮,所以筆者會在day 07再說明生命週期,若有不便敬請見諒。


上一篇
Day 04 Compoent及路由介紹
下一篇
Day 06 抽離C#程式碼
系列文
ASP.NET Core & Blazor30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言