ToB企服应用市场:ToB评测及商务社交产业平台

标题: .NET8依赖注入新特性Keyed services [打印本页]

作者: 嚴華    时间: 2023-12-22 07:59
标题: .NET8依赖注入新特性Keyed services
什么是Keyed service
Keyed service是指,为一个需要注入的服务定义一个Key Name,并使用使用Key Name检索依赖项注入 (DI) 服务的机制。


使用方法
通过调用 AddKeyedSingleton (或 AddKeyedScoped 或 AddKeyedTransient)来注册服务,与Key Name相关联。或使用 [FromKeyedServices] 属性指定密钥来访问已注册的服务。
以下代码演示如何使用Keyed service:
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.AspNetCore.SignalR;
  3. var builder = WebApplication.CreateBuilder(args);
  4. builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
  5. builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");
  6. builder.Services.AddControllers();
  7. var app = builder.Build();
  8. app.MapGet("/big", ([FromKeyedServices("big")] ICache bigCache) => bigCache.Get("date"));
  9. app.MapGet("/small", ([FromKeyedServices("small")] ICache smallCache) =>
  10.                                                                smallCache.Get("date"));
  11. app.MapControllers();
  12. app.Run();
  13. public interface ICache
  14. {
  15.     object Get(string key);
  16. }
  17. public class BigCache : ICache
  18. {
  19.     public object Get(string key) => $"Resolving {key} from big cache.";
  20. }
  21. public class SmallCache : ICache
  22. {
  23.     public object Get(string key) => $"Resolving {key} from small cache.";
  24. }
  25. [ApiController]
  26. [Route("/cache")]
  27. public class CustomServicesApiController : Controller
  28. {
  29.     [HttpGet("big-cache")]
  30.     public ActionResult<object> GetOk([FromKeyedServices("big")] ICache cache)
  31.     {
  32.         return cache.Get("data-mvc");
  33.     }
  34. }
  35. public class MyHub : Hub
  36. {
  37.     public void Method([FromKeyedServices("small")] ICache cache)
  38.     {
  39.         Console.WriteLine(cache.Get("signalr"));
  40.     }
  41. }
复制代码
Blazor中的支持
Blazor 现在支持使用 [Inject] 属性注入Keyed Service。 Keyed Service在使用依赖项注入时界定服务的注册和使用范围。
使用新 InjectAttribute.Key 属性指定服务要注入的Service:
  1. [Inject(Key = "my-service")]
  2. public IMyService MyService { get; set; }
复制代码
@inject Razor 指令尚不支持Keyed Service,但将来的版本会对此进行改进。 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4