我正在运行一些使用通用主机配置(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
您可以从IMessageSession
中解析IServiceProvider
,如后台工作程序中的here所示。