在 ASP.NET Core 2.x 中实现 EasyNetQ 发布/订阅模式的正确方法是什么?

Ant*_*ean 5 c# easynetq asp.net-core

我很好奇在 ASP.NET Core 2.x 应用程序中实现 EasyNetQ 发布/订阅模式的正确方法。具体来说,我需要确保所有这些资源的生命周期都是正确的,并且订阅线程拥有/正常运行。

我明白这IBus应该是一个单例。

标准做法是在应用程序的生命周期内创建单个 IBus 实例。当您的应用程序关闭时将其丢弃。

https://github.com/EasyNetQ/EasyNetQ/wiki/Connecting-to-RabbitMQ

所以,看起来像这样(尽管,我应该使用各种应用程序设置文件来提供特定于环境的连接字符串......让我们假设对于这个问题来说这是可以的)。

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IBus>(RabbitHutch.CreateBus("host=localhost"));
}
Run Code Online (Sandbox Code Playgroud)

现在,我喜欢自动订阅器功能,但何时何地运行各种订阅方法并不明显。

您可以使用它轻松扫描特定程序集以查找实现 IConsume 或 IConsumeAsync 接口的类,然后让自动订阅者将这些使用者订阅到您的总线。

直接在启动上下文中运行它似乎不太正确,对吗?

  • 订阅线程是否由正确的父线程“拥有”(是否有这样的事情)?
  • 的预期/正确生命周期是多少AutoSubscriberSingleton甚至是必要的?
  • 我真的想注册吗AutoSubscriber?我不希望任何其他代码需要它,我只需要它可以轻松/正确地访问Configure(似乎是运行类似方法的正确位置SubscribeAsync)。

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IBus>(RabbitHutch.CreateBus("host=localhost"));
    services.AddSingleton<AutoSubscriber>(provider => new AutoSubscriber(provider.GetRequiredService<IBus>(), Assembly.GetExecutingAssembly().GetName().Name));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.ApplicationServices.GetRequiredService<AutoSubscriber>().SubscribeAsync(Assembly.GetExecutingAssembly());
}
Run Code Online (Sandbox Code Playgroud)

我应该使用托管服务(我应该实现启动/停止方法还是BackgroundService可以)?

小智 2

我遇到了同样的难题。我发现您可以将容器中注册的任何内容注入 Startup::Configure 并执行一次性启动任务,就像使用 AutoSubscriber 一样。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IBus bus)
{
    var subscriber = new AutoSubscriber(bus, Assembly.GetExecutingAssembly().GetName().Name);
    subscriber.Subscribe(Assembly.GetExecutingAssembly());
}
Run Code Online (Sandbox Code Playgroud)