我正在按照以下方式配置服务总线
Startup.cs
services.AddSingleton<ServiceBusTransportOptions>(sp => JsonConvert.DeserializeObject<ServiceBusTransportOptions>(Configuration.GetSection("ServiceBus").Value));
库文件中的配置值如下
secrets.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;
的值未与库值映射。因此导致空指针体验
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();
}
无需手动反序列化。从配置绑定到对象模型,并显式注册所需的类型
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;
}
})