gpt4 book ai didi

c# - 依赖注入(inject)不适用于具有 Azure Key Vault 值 asp.net core 3.0 的 RabbitMQ 服务总线

转载 作者:行者123 更新时间:2023-12-04 10:45:27 24 4
gpt4 key购买 nike

我正在配置具有以下依赖关系的服务总线

启动.cs

services.AddSingleton<ServiceBusTransportOptions>(sp => JsonConvert.DeserializeObject<ServiceBusTransportOptions>(Configuration.GetSection("ServiceBus").Value));

保险库中的值如下
enter image description here

保险库文件中的配置值如下

secret .json
{
"ServiceBus": "{\"Transport\": \"RabbitMq\",\"RabbitMq\": {\"Url\": \"rabbitmq://localhost\",\"Username\": \"guest\",\"Password\": \"guest\"}}"
}

型号类
public class ServiceBusTransportOptions : IOptions<ServiceBusTransportOptions>
{
public TransportType Transport { get; set; } = TransportType.AzureServiceBus;

public AzureServiceBusTransportOptions AzureServiceBus { get; set; }

public RabbitMqTransportOptions RabbitMq { get; set; }

public ServiceBusTransportOptions Value => this;
}
var config = _.Resolve<IOptions<ServiceBusTransportOptions>>().Value; 的值默认不与 Vault 值映射。所以导致空指针错误

enter image description here

containerBuilder.Extension.cs
  public static void AddServiceBus(this ContainerBuilder builder,
string applicationName,
Action<IContainerBuilderConfigurator> configureMassTransitBuilder,
Action<IComponentContext, IBusFactoryConfigurator> configureServiceBus)
{
builder.Register(
_ =>
{
var config = _.Resolve<IOptions<ServiceBusTransportOptions>>().Value;
switch (config.Transport)
{
case TransportType.AzureServiceBus:
return new AzureServiceBusConfigurationProvider(config.AzureServiceBus.Value) as
IServiceBusConfigurationProvider;
case TransportType.RabbitMq:
return new RabbitMqServiceBusConfigurationProvider(config.RabbitMq.Value);
default:
return new InMemoryServiceBusConfigurationProvider() as
IServiceBusConfigurationProvider;
}

})
.As<IServiceBusConfigurationProvider>()
.SingleInstance();
}

最佳答案

无需手动反序列化。从配置绑定(bind)到对象模型,并显式注册所需的类型

var configuration = new ConfigurationBuilder()
.AddJsonFile("secret.json")
.Build();
//"ConfigurationBinder.Gett<T>" method comes from
// Microsoft.Extensions.Configuration.Binder.dll
ServiceBusTransportOptions options = configuration.GetSection("ServiceBus").Get<ServiceBusTransportOptions>();
services.AddSingleton(options);

并根据需要解决
//...
builder.Register(_ => {
var config = _.Resolve<ServiceBusTransportOptions>();
switch (config.Transport) {
case TransportType.AzureServiceBus:
return new AzureServiceBusConfigurationProvider(config.AzureServiceBus.Value) as
IServiceBusConfigurationProvider;
case TransportType.RabbitMq:
return new RabbitMqServiceBusConfigurationProvider(config.RabbitMq.Value);
default:
return new InMemoryServiceBusConfigurationProvider() as
IServiceBusConfigurationProvider;
}
})

关于c# - 依赖注入(inject)不适用于具有 Azure Key Vault 值 asp.net core 3.0 的 RabbitMQ 服务总线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59727220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com