什麼是Keyed service
Keyed service是指,為一個需要注入的服務定義一個Key Name,並使用使用Key Name檢索依賴項注入 (DI) 服務的機制。
使用方法
通過呼叫 AddKeyedSingleton (或 AddKeyedScoped 或 AddKeyedTransient)來註冊服務,與Key Name相關聯。或使用 [FromKeyedServices] 屬性指定金鑰來存取已註冊的服務。
以下程式碼演示如何使用Keyed service:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; var builder = WebApplication.CreateBuilder(args); builder.Services.AddKeyedSingleton<ICache, BigCache>("big"); builder.Services.AddKeyedSingleton<ICache, SmallCache>("small"); builder.Services.AddControllers(); var app = builder.Build(); app.MapGet("/big", ([FromKeyedServices("big")] ICache bigCache) => bigCache.Get("date")); app.MapGet("/small", ([FromKeyedServices("small")] ICache smallCache) => smallCache.Get("date")); app.MapControllers(); app.Run(); public interface ICache { object Get(string key); } public class BigCache : ICache { public object Get(string key) => $"Resolving {key} from big cache."; } public class SmallCache : ICache { public object Get(string key) => $"Resolving {key} from small cache."; } [ApiController] [Route("/cache")] public class CustomServicesApiController : Controller { [HttpGet("big-cache")] public ActionResult<object> GetOk([FromKeyedServices("big")] ICache cache) { return cache.Get("data-mvc"); } } public class MyHub : Hub { public void Method([FromKeyedServices("small")] ICache cache) { Console.WriteLine(cache.Get("signalr")); } }
Blazor中的支援
[Inject(Key = "my-service")] public IMyService MyService { get; set; }