经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
.NET8依赖注入新特性Keyed services
来源:cnblogs  作者:chester·chen  时间:2023/11/17 9:19:46  对本文有异议

什么是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,但将来的版本会对此进行改进。

 

原文链接:https://www.cnblogs.com/chenyishi/p/17835541.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号