.NET8依賴注入新特性Keyed services

什麼是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,但將來的版本會對此進行改進。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章