首页 > 其他分享 >.NET8依赖注入新特性Keyed services

.NET8依赖注入新特性Keyed services

时间:2023-11-16 10:24:05浏览次数:30  
标签:ICache Get big cache Keyed NET8 services public

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

 

标签:ICache,Get,big,cache,Keyed,NET8,services,public
From: https://www.cnblogs.com/chenyishi/p/17835541.html

相关文章

  • net8发布
    11月15日开始的为期三天的.NETConf在线活动的开幕日上,.NET8作为微软的开源跨平台开发平台正式发布。.NET团队着重强调云、性能、全栈Blazor、AI和.NETMAUI是.NET8的主要亮点。。NET团队在 .NETConf2023 [1]活动开幕式上表示:“通过这个版本,.NET重塑了我们构建按......
  • .NET之默认依赖注入 注入方式(构造函数注入、FromServices操作注入)和 获取服务(Contr
    .NET之默认依赖注入注入方式(构造函数注入、FromServices操作注入)和获取服务(Controller构造函数中注入获取、IServiceProvider获取、statrup中获取服务)介绍领券https://www.cps3.cn/不要依赖于具体的实现,应该依赖于抽象,高层模块不应该依赖于底层模块,二者应该依赖于抽......
  • Adding empty space into SQL Server Reporting Services
    REF:http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1400080&SiteID=1(1)Ratherthaninsertingspaces,canyouadjustthepaddingpropertyonthetextbox?Ifyougoalistohavethefieldindented,thatshouldwork.(2)Anyreasonyoucouldn'......
  • How to grant permissions to a custom assembly that is referenced in a report in
    Ref:http://support.microsoft.com/kb/842419/en-us HowtograntpermissionstoacustomassemblythatisreferencedinareportinReportingServicesViewproductsthatthisarticleappliesto.ArticleID:842419LastReview:April3,2007Revision:2.1OnThisPa......
  • .net core webapi Startup services.AddHttpClient
    staticpublicclassCreditScoreServiceExtension{staticpublicvoidAddCreditScoreQueryServiceHttpClient(thisIServiceCollectionservices,IConfigurationconfig){services.AddSingleton<ICreditScoreQueryService,CreditS......
  • Japan Registry Services (JPRS) Programming Contest 2023 (AtCoder Beginner Contes
    JapanRegistryServices(JPRS)ProgrammingContest2023(AtCoderBeginnerContest324)赛后总结可悲的是:我没来得及写题解。TaskASame秒切。直接输入排一遍序再遍历即可。#include<bits/stdc++.h>usingnamespacestd;intn,a[101];intmain(){cin>>n;......
  • .NET8 起步
    什么是.NET?.NET8.0SDK下载地址:https://dotnet.microsoft.com/zh-cn/download/dotnet/8.0.NET是一个免费的跨平台开源开发人员平台,用于生成许多不同类型的应用。使用.NET,可以使用多种语言(C#、F#、VB)、编辑器(VS、VSC、Rider)和库(以Microsoft主导的社区提供超过100,000+包来)来......
  • .NET8 Hello World!
    使用ASP.NETCoreWebApplication模板创建的Empty项目如下:这是一个最简单的Web项目,运行起来会在根路径响应HelloWorld! Programe代码非常简洁,但内容非常不简单。varbuilder=WebApplication.CreateBuilder(args);//1创建WebApplication构建者varapp=builder.Bu......
  • Lightsail CDN 现已对 Lightsail Container Services 作为来源进行支持
    AmazonLightsail 现在通过将LightsailCDN与您的LightsailContainerServices结合使用,为您提供了优化向全球受众交付容器化应用程序的功能。只需从Lightail控制台点击几下,Lightail容器就可以配置为LightsailCDN分配的来源。亚马逊云科技开发者社区为开发者们提供全......
  • gitlab--services、environment、inherit
    servicesservices 关键字定义了一个Docker镜像,该镜像在链接到image关键字定义的Docker镜像的 job 期间运行。这允许您在构建期间访问服务镜像。服务镜像可以运行任何应用程序,但最常见的用例是运行数据库容器,例如:MySQLPostgreSQLRedis例如,每次构建项目时,使用现有镜像并将其......