我正在运行一些使用通用主机配置 ( https://docs.particular.net/samples/hosting/generic-host/ ) 构建的 NServiceBus 端点。这些端点在 Docker 容器中运行。现在,我想安排一条消息(使用hangfire)。每当执行预定的消息时,我都会收到以下错误:
Value cannot be null. (Parameter 'session')
System.ArgumentNullException: Value cannot be null. (Parameter 'session')
at NServiceBus.Guard.AgainstNull(String argumentName, Object value)
at NServiceBus.IMessageSessionExtensions.Send(IMessageSession session, Object message)
at Provisioning.Handlers.CustomerCreatedHandler.Reauthenticate(Guid customerId) in /src/Provisioning/Handlers/CustomerCreatedHandler.cs:line 30
这是因为 Send() 方法没有消息会话。但是,我如何获得这个会话?查看https://docs.particular.net/nservicebus/hosting/,您可以通过从 EndpointConfiguration 启动新端点来创建会话。由于我使用通用主机,我只有 EndpointConfiguration 但我无权访问由此创建的端点(或者至少我不知道如何)。这是我的配置的样子(非常简化):
hostBuilder = Host.CreateDefaultBuilder()
.UseConsoleLifetime()
.UseNServiceBus(xtc =>
{
var endpointConfiguration = new EndpointConfiguration("endpointName");
endpointConfiguration.UseSerialization<NewtonsoftSerializer>();
endpointConfiguration.EnableInstallers();
endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
// removed all config
return endpointConfiguration;
});
这是从以下开始的:
await hostBuilder.Build().RunAsync();
顺便说一句,我正在使用 NServiceBus 7。
编辑:
这就是我安排 Hangfire 任务的方式(根据 Szymon 的回答更新,但还没有工作):
public class CustomerCreatedHandler : IHandleMessages<CustomerCreated>
{
private static IServiceProvider _provider;
public CustomerCreatedHandler(IServiceProvider provider)
{
_provider = provider;
}
public async Task Handle(CustomerCreated message, IMessageHandlerContext context)
{
RecurringJob.AddOrUpdate($"Reauthenticate-{message.CustomerId}", () => Reauthenticate(message.CustomerId), Cron.Hourly);
}
public static Task Reauthenticate(Guid customerId)
{
IMessageSession session = _provider.GetService<IMessageSession>();
return session.Send(new AuthenticateCustomer { CustomerId = customerId });
}
}
结果是:
System.ArgumentNullException
Value cannot be null. (Parameter 'provider')
System.ArgumentNullException: Value cannot be null. (Parameter 'provider')
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at Provisioning.Handlers.CustomerCreatedHandler.Reauthenticate(Guid customerId) in /src/Provisioning/Handlers/CustomerCreatedHandler.cs:line 33