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, ...
随机推荐
- 浅谈数栈产品里的 Descriptions 组件
我们是袋鼠云数栈 UED 团队,致力于打造优秀的一站式数据中台产品.我们始终保持工匠精神,探索前端道路,为社区积累并传播经验价值. 本文作者:修能 What's? 数栈产品里的 Description ...
- 《MySQL 5.7从入门到精通(视频教学版)》代码课件教学视频下载
<MySQL 5.7从入门到精通(视频教学版)>代码课件教学视频下载 https://pan.baidu.com/s/1ZufDV6a_PEnjp-Bdh4IkuQ 提取码:vgnr 无版 ...
- [rCore学习笔记 028] Rust 中的动态内存分配
引言 想起我们之前在学习C的时候,总是提到malloc,总是提起,使用malloc现场申请的内存是属于堆,而直接定义的变量内存属于栈. 还记得当初学习STM32的时候CubeIDE要设置stack 和 ...
- Linux Kernel Utilization Clamping简介
随着linux内核调度技术的不断演进,目前存在多个调度类(stop.deadline.rt.cfs.idle)以满足不同性质和要求的任务(task)的调度需求.对于用户空间来说,完全公平调度器(CFS ...
- python处理nii文件
第一步安装nibabel,可以使用命令:pip install nibabel 之后: from nibabel.viewers import OrthoSlicer3D as osdimport n ...
- es6有哪些新特性?
1. let 和 ocnst ,可以定义块级作用域 2. 新增了箭头函数,箭头函数简化了函数定义的定义 3.新增了promise解决回调地狱问题 ps:回调地狱是我们异步请求服务器数据时,通过then ...
- 在 Kubernetes 中部署并使用 KubeEdge
作者:马伟,青云科技容器顾问,云原生爱好者,目前专注于云原生技术,云原生领域技术栈涉及 Kubernetes.KubeSphere.KubeKey 等. 边缘计算在广泛制造业.工业.零售和金融等行业, ...
- 五分钟一百行代码,手写一个vue项目全局通用的toast提示组件
前言: 我们已经分享过如何快速实现自己需要的全局弹框组件: 在开发 Vue 项目时,特别是H5页面的项目,还有一个组件是我们非常常用的,它相对弹框来说没有那么大,并且不需要手动关闭在需要更简洁的提示用 ...
- 快速上手web前端开发(超详细教程)
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 第一步 下安装vscode 第二步 vscode汉化 第三步 安装前端所需插件 1.Live Server 2.Jav ...
- AI绘画漫谈——从AI网页生成说起
1. 又说"前端已死" 为什么说"又"呢?因为前两年我在一些博客网站三天两头就能看到这个标题,虽然今年好像换话题了,但感觉前端每年都要死个七八次,当然这里面还是 ...