.NET8依赖注入新特性Keyed services
  OaxsuEwyxUZi 2023年11月17日 139 0

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

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月17日 0

暂无评论

推荐阅读
  NPQODODLqddb   2024年05月17日   63   0   0 .NET
  mVIyUuLhKsxa   2024年05月17日   50   0   0 .NET
  XkHDHG7Y62UM   2024年05月17日   42   0   0 .NET
  f18CFixvrKz8   2024年05月18日   78   0   0 .NET
  rBgzkhl6abbw   2024年05月18日   71   0   0 .NET
  MYrYhn3ObP4r   2024年05月17日   39   0   0 .NET
  S34pIcuyyIVd   2024年05月17日   55   0   0 .NET
  gKJ2xtp6I8Y7   2024年05月17日   49   0   0 .NET
  MYrYhn3ObP4r   2024年05月17日   32   0   0 .NET
OaxsuEwyxUZi