.NET8依赖注入新特性Keyed services services 依赖注入新特性 Keyed .NET NET8 NET
什么是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中的支持
使用新 InjectAttribute.Key 属性指定服务要注入的Service:
[Inject(Key = "my-service")] public IMyService MyService { get; set; }@inject Razor 指令尚不支持Keyed Service,但将来的版本会对此进行改进。