冠军

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

NATS: 对依赖注入支持

NuGet:

使用方法:

serviceCollection.AddNats();

在容器中添加了 2 个单例服务:

  1. NATS.Client.Core.NatsConnection 实际类型
  2. NATS.Client.Core.INatsConnection ,接口类型

所以在注入的时候,既可以使用接口注入,也可以使用实际类型注入。

具体定义

  • 当指定 poolSize 为 1 的时候,注册了单例的 NatsConnectionINatsConnection
  • 否则,将 NatsConnectionPool 注册为单例,而 NatsConnectionINatsConnection 通过从池中获得而实现为瞬态。
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using NATS.Client.Core;

namespace NATS.Client.Hosting;

public static class NatsHostingExtensions
{
    /// <summary>
    /// Add NatsConnection/Pool to ServiceCollection. When poolSize = 1, registered `NatsConnection` and `INatsConnection` as singleton.
    /// Others, registered `NatsConnectionPool` as singleton, `NatsConnection` and `INatsConnection` as transient(get from pool).
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:Commas should not be preceded by whitespace", Justification = "Required for conditional build.")]
    [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1009:Closing parenthesis should not be preceded by a space", Justification = "Required for conditional build.")]
    [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1111:Closing parenthesis should be on the same line as the last parameter", Justification = "Required for conditional build.")]
    [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1113:Comma should be on the same line as previous parameter", Justification = "Required for conditional build.")]
    public static IServiceCollection AddNats(
        this IServiceCollection services,
        int poolSize = 1,
        Func<NatsOpts, NatsOpts>? configureOpts = null,
        Action<NatsConnection>? configureConnection = null
#if NET8_0_OR_GREATER
        , object? key = null // This parameter is only available in .NET 8 or greater
#endif
    )
    {
        object? diKey = null;
#if NET8_0_OR_GREATER
        diKey = key;
#endif

        poolSize = Math.Max(poolSize, 1);

        if (poolSize != 1)
        {
            NatsConnectionPool PoolFactory(IServiceProvider provider)
            {
                var options = NatsOpts.Default with
                {
                    LoggerFactory = provider.GetRequiredService<ILoggerFactory>(),
                };
                if (configureOpts != null)
                {
                    options = configureOpts(options);
                }

                return new NatsConnectionPool(poolSize, options, configureConnection ?? (_ => { }));
            }

            static NatsConnection ConnectionFactory(IServiceProvider provider, object? key)
            {
#if NET8_0_OR_GREATER
                if (key == null)
                {
                    var pool = provider.GetRequiredService<NatsConnectionPool>();
                    return (pool.GetConnection() as NatsConnection)!;
                }
                else
                {
                    var pool = provider.GetRequiredKeyedService<NatsConnectionPool>(key);
                    return (pool.GetConnection() as NatsConnection)!;
                }
#else
                var pool = provider.GetRequiredService<NatsConnectionPool>();
                return (pool.GetConnection() as NatsConnection)!;
#endif
            }

            if (diKey == null)
            {
                services.TryAddSingleton(PoolFactory);
                services.TryAddSingleton<INatsConnectionPool>(static provider => provider.GetRequiredService<NatsConnectionPool>());
                services.TryAddTransient<NatsConnection>(static provider => ConnectionFactory(provider, null));
                services.TryAddTransient<INatsConnection>(static provider => provider.GetRequiredService<NatsConnection>());
            }
            else
            {
#if NET8_0_OR_GREATER
                services.TryAddKeyedSingleton(diKey, (provider, _) => PoolFactory(provider));
                services.TryAddKeyedSingleton<INatsConnectionPool>(diKey, static (provider, key) => provider.GetRequiredKeyedService<NatsConnectionPool>(key));
                services.TryAddKeyedTransient<NatsConnection>(diKey, static (provider, key) => ConnectionFactory(provider, key));
                services.TryAddKeyedTransient<INatsConnection>(diKey, static (provider, key) => provider.GetRequiredKeyedService<NatsConnection>(key));
#endif
            }
        }
        else
        {
            NatsConnection Factory(IServiceProvider provider)
            {
                var options = NatsOpts.Default with
                {
                    LoggerFactory = provider.GetRequiredService<ILoggerFactory>(),
                };
                if (configureOpts != null)
                {
                    options = configureOpts(options);
                }

                var conn = new NatsConnection(options);
                if (configureConnection != null)
                {
                    configureConnection(conn);
                }

                return conn;
            }

            if (diKey == null)
            {
                services.TryAddSingleton(Factory);
                services.TryAddSingleton<INatsConnection>(static provider => provider.GetRequiredService<NatsConnection>());
            }
            else
            {
#if NET8_0_OR_GREATER
                services.TryAddKeyedSingleton<NatsConnection>(diKey, (provider, _) => Factory(provider));
                services.TryAddKeyedSingleton<INatsConnection>(diKey, static (provider, key) => provider.GetRequiredKeyedService<NatsConnection>(key));
#endif
            }
        }

        return services;
    }
}

See: https://github.com/nats-io/nats.net.v2/tree/main/src/NATS.Client.Hosting

posted on   冠军  阅读(52)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示