从单例运行Dotnet 3.1后台服务

问题描述

我在StartUp上初始化了一个后台服务,我仅将此服务用于队列使用方。它使用具有订阅方法的单例服务来处理队列消耗。 作为对StartUp的单例初始化,我希望它只会建立一个连接,但是在我收到的每个队列消息之后,它正在创建一个新的连接。我想知道如何为消费者建立一个连接。 我正在使用dotnet 3.1和rabbitMQClient lib

我的代码如下:

我这样将我的单例注入到我的启动中

public void ConfigureServices(IServiceCollection services)
{
           
    services.AddSingleton<EasyNetQMessageQueuer<RegisterUserResponseEvent>>();
    services.AddControllers();
}

然后在这样的Configure方法添加后台服务:

public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
     }

     app.UseRouting();

     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
     });

     app.UseQueueConsumer();
}

此后勤服务来自以下此类:

private static EasyNetQMessageQueuer<RegisterUserResponseEvent> _queuer;

public static IApplicationBuilder UseQueueConsumer(this IApplicationBuilder app)
{
    _queuer = app.applicationservices.GetService<EasyNetQMessageQueuer<RegisterUserResponseEvent>>();
    var lifetime = app.applicationservices.GetService<IHostApplicationLifetime>();

    lifetime.ApplicationStarted.Register(OnStarted);
    lifetime.ApplicationStopped.Register(OnStopping);

    return app;
}
        
private static void OnStarted()
{
    _queuer.Subscribe();
}
private static void OnStopping()
{
    _queuer.disposeConnection();
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...