什么是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中的支持
Blazor 现在支持使用 [Inject] 属性注入Keyed Service。Keyed Service在使用依赖项注入时界定服务的注册和使用范围。
使用新 InjectAttribute.Key 属性指定服务要注入的Service:
[Inject(Key = "my-service")]public IMyService MyService { get; set; }
@inject Razor 指令尚不支持Keyed Service,但将来的版本会对此进行改进。
参考地址
https://learn.microsoft.com/zh-cn/aspnet/core/release-notes/aspnetcore-8.0?view=aspnetcore-8.0#keyed-services-support-in-dependency-injection
https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-8.0#keyed-services
https://learn.microsoft.com/zh-cn/aspnet/core/release-notes/aspnetcore-8.0?view=aspnetcore-7.0#inject-keyed-services-into-components
关注我获取技术分享





