首页 > 其他分享 >NET8中增加的简单适用的DI扩展库Microsoft.Extensions.DependencyInjection.AutoActivation

NET8中增加的简单适用的DI扩展库Microsoft.Extensions.DependencyInjection.AutoActivation

时间:2024-06-11 16:54:50浏览次数:30  
标签:serviceKey DI IServiceCollection AutoActivation static NET8 services Type public

这个库提供了在启动期间实例化已注册的单例,而不是在首次使用它时实例化。

单例通常在首次使用时创建,这可能会导致响应传入请求的延迟高于平时。在注册时创建实例有助于防止第一次Request请求的SLA

以往我们要在注册的时候启动单例可能会这样写:

//注册:
services.AddSingleton<FileChangeNotifier>();
//初始化
using var scope = services.BuildServiceProvider().CreateScope();
scope.ServiceProvider.GetRequiredService<FileChangeNotifier>();

但是借助Microsoft.Extensions.DependencyInjection.AutoActivation 我们的写法就特别的简单了:

//注册服务,并直接实例化
services.AddActivatedSingleton<FileChangeNotifier>();

AutoActivation扩展库其实相当简单,内部实现了一个AutoActivationHostedService的 HostedService,当系统启动的时候就从IServiceProvider中取到所有注册为AutoActivation的单例,下面是他的源码:

internal sealed class AutoActivationHostedService : IHostedService
{
    private readonly AutoActivatorOptions _options;
    private readonly IServiceProvider _provider;

    public AutoActivationHostedService(IServiceProvider provider, IOptions<AutoActivatorOptions> options)
    {
        _provider = provider;
        _options = Throw.IfMemberNull(options, options.Value);
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        foreach (var singleton in _options.AutoActivators)
        {
            _ = _provider.GetRequiredService(singleton);
        }

        foreach (var (serviceType, serviceKey) in _options.KeyedAutoActivators)
        {
            _ = _provider.GetRequiredKeyedService(serviceType, serviceKey);
        }

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

当然提供的扩展不限于AddActivatedSingleton<T>一个,还有如下的扩展方法:

public static IServiceCollection ActivateSingleton<TService>(this IServiceCollection services)
public static IServiceCollection ActivateSingleton(this IServiceCollection services, Type serviceType)
public static IServiceCollection AddActivatedSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory)
public static IServiceCollection AddActivatedSingleton<TService, TImplementation>(this IServiceCollection services)
public static IServiceCollection AddActivatedSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory)
public static IServiceCollection AddActivatedSingleton<TService>(this IServiceCollection services)
public static IServiceCollection AddActivatedSingleton(this IServiceCollection services, Type serviceType)
public static IServiceCollection AddActivatedSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
public static IServiceCollection AddActivatedSingleton(this IServiceCollection services, Type serviceType, Type implementationType)
public static void TryAddActivatedSingleton(this IServiceCollection services, Type serviceType)
public static void TryAddActivatedSingleton(this IServiceCollection services, Type serviceType, Type implementationType)
public static void TryAddActivatedSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
public static void TryAddActivatedSingleton<TService>(this IServiceCollection services)
public static void TryAddActivatedSingleton<TService, TImplementation>(this IServiceCollection services)
public static void TryAddActivatedSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory)
 
public static IServiceCollection ActivateKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey)
public static IServiceCollection ActivateKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey)
public static IServiceCollection AddActivatedKeyedSingleton<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory)
public static IServiceCollection AddActivatedKeyedSingleton<TService, TImplementation>(this IServiceCollection services, object? serviceKey)
public static IServiceCollection AddActivatedKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory)
public static IServiceCollection AddActivatedKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey)
public static IServiceCollection AddActivatedKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey)
public static IServiceCollection AddActivatedKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
public static IServiceCollection AddActivatedKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Type implementationType)
public static void TryAddActivatedKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey)
public static void TryAddActivatedKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Type implementationType)
public static void TryAddActivatedKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
public static void TryAddActivatedKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey)
public static void TryAddActivatedKeyedSingleton<TService, TImplementation>(this IServiceCollection services, object? serviceKey)
public static void TryAddActivatedKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory)

最近我在Biwen.Settings添加了对JSON配置监听的功能,有这方面的需求,最初是有一个Start方法,也就是启动系统的时候获取服务然后调用Start方法,如果使用了AutoActivation 那Start的方法体可以直接使用构造函数替代,这个也是除了开头解决SLA以外的一个用例吧

有任何不足的地方欢迎小伙伴们留言指正

标签:serviceKey,DI,IServiceCollection,AutoActivation,static,NET8,services,Type,public
From: https://www.cnblogs.com/vipwan/p/18242343

相关文章

  • Redis:原理、概念、用法与实例解析
    Redis:原理、概念、用法与实例解析在当今风起云涌的技术领域中,Redis犹如一颗璀璨的明星,闪耀着独特的光芒。它作为一种备受瞩目的数据存储和缓存解决方案,以其卓越的性能、丰富多样的功能以及简单易用的特性,成为了众多开发者的心头好。在这篇博客中,我们将全方位、深层次地探......
  • Redis之发布订阅
    发布订阅Redis发布订阅(pub/sub)是一种消息通信模式,发送者(pub)发送消息,订阅者(sub)接收消息。Redis客户端可以订阅任意数量的频道。消息发送者&消息接收者&频道可以想象这么一个场景。我们抖音、微博关注了哪个博主,当他发布一条文章时,系统就会给我们推送他发布的消息内......
  • 理解dispatch_async
    Submitsablockforasynchronousexecutiononadispatchqueueandreturnsimmediately.提交一个块以在调度队列上异步执行并立即返回。codeshowing以一个最简单的demo开始//创建一个同步队列dispatch_queue_tsyncQueue=dispatch_queue_create("io.sqi.My......
  • 百度面试:如何用Redis实现限流?
    高并发系统有三大特征:限流、缓存和熔断,所以限流已经成为当下系统开发中必备的功能了。那么,什么是限流?如何实现限流?使用Redis能不能实现限流?接下来我们一起来看。1.什么是限流?限流是指在各种应用场景中,通过技术和策略手段对数据流量、请求频率或资源消耗进行有计划的限制,以避......
  • Stable diffusion 再现女皇武则天,SD图文教程
    本次教程使用的是文生图功能本次教程按照从上到下的操作顺序如下:①选好大模型,②输入关键词,③选好LORA模型,④设置出图参数,⑤设置ControlNet大模型:majicMIXrealistic麦橘写实_v7大模型可以在这里搜索,点击加入模型库就行了https://www.liblib.artStablediffus......
  • vue3 高德安徽省边界 密钥必须添加否则会出现无法使用DistrictSearch的方法也不报错
    <template> <divclass="centermap"ref="mapContainer"></div></template><scriptsetuplang="ts">import{ref,onMounted}from'vue';importAMapLoaderfrom'@amap/amap-jsapi-l......
  • redis自学(46)键值设计
    Redis键值设计优雅的key结构Redis的Key虽然可以自定义,到但是最好遵循下面的几个最佳实践约定:l 遵循基本格式:[业务名称]:[数据名]:[id]l 长度不超过44字节(长度越小,占用的内存越少)l 不包含特殊字符  优点:①可读性强②避免key冲突③方便管理④更节省内存:ke......
  • Auto Arena of LLMs: Automating LLM Evaluations with Agent Peer-battles and Commi
    1.引言大语言模型(LLMs)发展迅速,亟需可靠的评估方法。静态数据集存在污染风险,人工评估平台耗时费力。提出自动、可靠、可信的评估框架:Auto-ArenaofLLMs(Auto-Arena)。2.相关工作自动评估方法:静态数据集和基于模型的评估。人工评估平台:ChatbotArena,存在耗时和语言......
  • Redis面试题、知识点总结,一篇文章让Redis成为面试加分项
    Redis面试题、知识点总结,一篇文章让Redis成为面试加分项前言参与了几次中大厂的面试,你会发现一面时对于八股文的考察也具有侧重点(MySQL=Redis>网络>系统>设计模式>java集合>JVM>spring)本文的目标就是通过这一篇文章让你能在面试时将Redis相关的问题回答漂亮。......
  • Dijkstra 算法的手动分析
    目录Dijkstra算法step0.初始状态step1.第一轮step2.第二轮step3.第三轮step4.第四轮Dijkstra算法以下面有向图为例:graphLRV0((V0))--10-->V1((V1))V0((V0))--5-->V4((V4))V1((V1))--2-->V4((V4))V4((V4))--3-->V1((V1))V1((V1))--1-->V2((V2)......