Dependency Injection 觀摩筆記 (DI & IOC)
2023-12-10
觀摩 Blazored/LocalStorage
關於 Interface 設計與 Dependency Injection 的使用方式,從真實案例學習使用 Dependency Injection 🙂
說明
// Program.cs 🐧
builder.Services.AddBlazoredLocalStorageAsSingleton();
public static IServiceCollection AddBlazoredLocalStorage
services.TryAddScoped<IStorageProvider, BrowserStorageProvider>();
services.TryAddScoped<ILocalStorageService, LocalStorageService>();
// BrowserStorageProvider.cs 🐧
public BrowserStorageProvider(IJSRuntime jSRuntime)
{
_jSRuntime = jSRuntime;
_jSInProcessRuntime = jSRuntime as IJSInProcessRuntime;
}
await _jSRuntime.InvokeVoidAsync("localStorage.clear", cancellationToken);
// LocalStorageService.cs 🐧
public LocalStorageService(IStorageProvider storageProvider, IJsonSerializer serializer)
{
_storageProvider = storageProvider;
_serializer = serializer;
}
當你註冊 services.TryAddScoped<ILocalStorageService, LocalStorageService>(); 時,ASP.NET Core 的依賴注入容器會自動查找已經註冊的依賴並將它們注入到 LocalStorageService 的實例中。容器會檢查 LocalStorageService 的建構子,並根據建構子參數的類型自動解析已經註冊的相應服務。
所以,如果你之前已經註冊了 IStorageProvider 和 IJsonSerializer 的實現類型,而這些實現類型已經被註冊為 Scoped 服務,那麼當你註冊 ILocalStorageService 時,容器將自動查找這些依賴並注入到 LocalStorageService 的實例中。