NATS: 对依赖注入支持
NuGet:
使用方法:
serviceCollection.AddNats();
在容器中添加了 2 个单例服务:
- NATS.Client.Core.NatsConnection 实际类型
- NATS.Client.Core.INatsConnection ,接口类型
所以在注入的时候,既可以使用接口注入,也可以使用实际类型注入。
具体定义
- 当指定 poolSize 为 1 的时候,注册了单例的
NatsConnection和INatsConnection。 - 否则,将
NatsConnectionPool注册为单例,而NatsConnection和INatsConnection通过从池中获得而实现为瞬态。
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
NATS: 对依赖注入支持的更多相关文章
- 封装了一些sqlsugar的常用方法 用来动态切换数据库和依赖注入 支持泛型
接口: /// <summary> /// 数据库操作 /// </summary> public interface IDAL_Services { /// <summ ...
- ASP.NET Core 中文文档 第四章 MVC(4.4)依赖注入和控制器
原文: Dependency Injection and Controllers 作者: Steve Smith 翻译: 刘浩杨 校对: 孟帅洋(书缘) ASP.NET Core MVC 控制器应通过 ...
- 开涛spring3(12.2) - 零配置 之 12.2 注解实现Bean依赖注入
12.2 注解实现Bean依赖注入 12.2.1 概述 注解实现Bean配置主要用来进行如依赖注入.生命周期回调方法定义等,不能消除XML文件中的Bean元数据定义,且基于XML配置中的依赖注入的 ...
- Unity文档阅读 第三章 依赖注入与Unity
Introduction 简介In previous chapters, you saw some of the reasons to use dependency injection and lea ...
- 注解实现Bean依赖注入
12.2.1 概述 注解实现Bean配置主要用来进行如依赖注入.生命周期回调方法定义等,不能消除XML文件中的Bean元数据定义,且基于XML配置中的依赖注入的数据将覆盖基于注解配置中的依赖注入的数 ...
- ASP.NET Core 中的框架级依赖注入
https://tech.io/playgrounds/5040/framework-level-dependency-injection-with-asp-net-core 作者: Gunnar P ...
- ASP.NET Core MVC 之依赖注入 Controller
ASP.NET Core MVC 控制器应通过构造函数明确地请求它们地依赖关系,在某些情况下,单个控制器地操作可能需要一个服务,在控制器级别上的请求可能没有意义.在这种情况下,也可以将服务作为 Ac ...
- ThinkPHP6.0 容器和依赖注入
ThinkPHP6.0 容器和依赖注入 分为如下两部分: 依赖注入 容器 依赖注入 依赖注入其实本质上是指对类的依赖通过构造器完成自动注入: 在控制器架构方法和操作和方法中一旦对参数进行对象类型约束则 ...
- 018-019 NET5_内置容器支持依赖注入+IServiceCollection的生命周期
概念: DI依赖注入: IServiceCollection仅支持构造函数注入 什么是依赖注入? 如果对象A依赖对象B,对象B依赖对象C,就可以先构造对象C,然后传递给对象B,再把对象B传递给A.得到 ...
- 创建支持依赖注入、Serilog 日志和 AppSettings 的 .NET 5 控制台应用
翻译自 Mohamad Lawand 2021年3月24日的文章 <.NET 5 Console App with Dependency Injection, Serilog Logging, ...
随机推荐
- 八字测算api接口数据示例_奥顺八字测算接口分享
八字测算免费api接口,每日开放时间在早上8点到晚上十点,本api接口完全免费,是奥顺居八字测算网程序内部接口,提供本地调用的,现在免费分享出来,仅供测试. 接口名称:八字精批测算api接口示例 接口 ...
- Android usb广播 ACTION_USB_DEVICE_ATTACHED流程源码分析
整体流程图 大概意思就是UsbHostManager启动监控线程,monitorUsbHostBus会调用usb_host_run函数(使用inotify来监听USB设备的插拔)不停的读取bus总线, ...
- vue2 + webpack 分析报告 report == webpack-bundle-analyzer
packjson.js 配置 "build-report":"vue-cli-service build --report", 执行 : npm run bui ...
- JOI Open 2017(口胡)
T1 Amusement Park 题意:通信题.给定一张 \(n\) 个点 \(m\) 条边的无向连通图.Alice 会得到一个 \([0, 2^{60})\) 中的数 \(x\),并且她需要给这张 ...
- 集成InfluxDb, telegraf, Grafana, App Metrics以记录性能指标
前情概要 刚好有半天得闲功夫, 从项目里面找个功能来水一篇文章. 上线的项目通常都是需要做性能数据收集工作的, 它好处就不想打字了. 业界有很多套方案, 工具[收费的, 免费的], 收集采用[拉取的, ...
- HTTP常见状态码详细解析
HTTP状态码(英语:HTTP Status Code)是用以表示网页服务器 超文本传输协议响应状态的3位数字代码. 它由 RFC 2616 规范定义的,并得到 RFC 2518.RFC 2817.R ...
- vue,js直接导出excel,xlsx的方法,XLSX_STYLE 行高设置失效的问题解决,冻结窗体修改支持
1.先安装依赖:xlsx.xlsx-style.file-saver三个包 npm install xlsx xlsx-style file-saver 出现错误: This relative mod ...
- 【Python】公众号聚合登录软件+源码
废话不多说了,直接上图,回复拿软件和源码[自己打包,配置环境比较复杂] 写这个软件就是因为其他平台的会员太贵了,还不如自己写个,不限制账号登录数~ 授权,打开和删除功能都是正常的, 面板功能,我打算做 ...
- “地表最强”人形机器人亮相:视觉&语音推理能力
Figure 02配备了机载的视觉语言模型(VLM),使其能够进行快速的常识性视觉推理. 相关: https://mbd.baidu.com/newspage/data/landingsuper?co ...
- Linux /dev/loop0文件详解
loop设备介绍 在类 UNIX 系统里,loop 设备是一种伪设备(pseudo-device),或者也可以说是仿真设备.它能使我们像块设备一样访问一个文件. 在使用之前,一个 loop 设备必须要 ...