MVC 核心中的 NServiceBus - 使用依赖注入发送

NServiceBus In MVC Core - Sending with Dependency Injection

我目前正在尝试通过 NServiceBus 7.1.9 将消息发送到 Azure ServiceBus 队列。

我们正在使用

但是,消息似乎已发送,但从未到达目标队列。

我们正在尝试使用默认的 Microsoft 依赖注入,它再次显示配置正确,但不发送任何消息。

startup.cs我们配置服务并添加到DI容器

private void ConfigureNServiceBus(IServiceCollection services)
    {
        // Sending Service
        services.AddScoped<IServiceBusSender, ServiceBusSender>();

        // Create endpoint
        var endpointConfiguration = new EndpointConfiguration("LinkGreenEndpoint");

        // Set Queue Name
        var context = Configuration["ServiceBusContext"]?.ToLower() ?? "local";
        endpointConfiguration.OverrideLocalAddress($"horticulture.nservicebusbackend.{context}");
        // Use Azure ServiceBus Queue
        var transport = endpointConfiguration.UseTransport<AzureServiceBusTransport>();
        transport.ConnectionString(Configuration["ConnectionStrings:LinkGreenServiceBus"]);
        // ConnectionStrings:LinkGreenServiceBus= "Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxx"

        endpointConfiguration.UsePersistence<AzureStoragePersistence>();

        endpointConfiguration.UseContainer<ServicesBuilder>(customizations =>
        {
            customizations.ExistingServices(services);
        });


        var endpoint = NServiceBus.Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();

        // Add to Dependency Injection Container        
        services.AddScoped(typeof(IEndpointInstance), x => endpoint);

    }

要发送消息,我们使用 ServiceBusSender

 public class ServiceBusSender : IServiceBusSender
    {
        private readonly IEndpointInstance _endpointInstance;
        public ServiceBusSender(IEndpointInstance endpointInstance)
        {
            _endpointInstance = endpointInstance;
        }

        public Task Send(ICommand message)
        {
            // Also tried _endpointInstance.SendLocal(); - gives "handler not found"
            return _endpointInstance.Send(message);
        }
    }

以及我们发送的命令示例:

 public class CloneSupplierItemCommandBase : ICommand
    {
        public int BuyerId { get; set; }

        public IdAndQuantity[] CloneItems { get; set; }
    }

我们目前成功地将 .NET 4.5 中的 NServiceBus v5.0.0 与此 ServiceBus 端点一起使用。

找到问题并设法将消息发布到队列中。

不能 100% 确定以下哪个是解​​决方案

将创建时的队列名称设置为端点

var context = Configuration["ServiceBusContext"]?.ToLower() ?? "local";
var endpointConfiguration = new EndpointConfiguration($"horticulture.nservicebusbackend.{context}");

将端点名称添加到 Send() 命令

return _endpointInstance.Send(_endpoint, message);

您在 ConfigureNServiceBus 方法中的端点配置似乎没有定义任何路由。没有这个,端点将不知道将命令消息传递到哪里。

我怀疑您之所以成功,是因为您直接在 Send() 命令中添加了目标端点名称。这行得通,但是当你有很多端点时它会变得难以管理 and/or 你想在 run-time.

修改路由

更好的方法是在启动时配置路由。请参阅 Particular 文档站点上的 Command Routing