0

Summary i do how it resolved in Setup RabbitMQ consumer in ASP.NET Core application but my Rabbit consumer online if i do web request, if i start IIS and don't start browser request, Rabbit consumer is not started. Have any one know why? Can a web application do the work of a web application and a Windows service or is it a bad idea.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton<RabbitListener>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseRabbitListener();
        ...
    }

}
public static class ApplicationBuilderExtentions
{
    //the simplest way to store a single long-living object, just for example.
    private static RabbitListener _listener { get; set; }

    public static IApplicationBuilder UseRabbitListener(this IApplicationBuilder app)
    {
        _listener = app.ApplicationServices.GetService<RabbitListener>();


        var lifetime = app.ApplicationServices.GetService<IApplicationLifetime>();

        lifetime.ApplicationStarted.Register(OnStarted);

        //press Ctrl+C to reproduce if your app runs in Kestrel as a console app
        lifetime.ApplicationStopping.Register(OnStopping);

        return app;
    }

    private static void OnStarted()
    {
        foreach (var o in LogOptions.Options)
            _listener.NewRouteAdd(o.QueueString);
        _listener.Register();
    }

    private static void OnStopping()
    {
        _listener.Deregister();
    }
}
3
  • Services are only started once they are actually used. So on starting up the application on IIS you need to explicitly make a call to a method/route that uses the service. At least that's how we solved this issue before. Commented May 8, 2019 at 9:20
  • Maby it can be call in "static main",before create service or any one net mvc object can do it? Commented May 8, 2019 at 10:23
  • so now we have background worker ihostedservice :) Commented Jul 8, 2021 at 14:27

1 Answer 1

0

The OnStart() runs once, when your application receives the first HTTP request I think the best option for you is to create a Windows Service for consuming messages or any application that keeps alive connection

I suggest for you these links: https://www.cloudamqp.com/blog/2018-01-19-part4-rabbitmq-13-common-errors.html https://www.cloudamqp.com/blog/2017-12-29-part1-rabbitmq-best-practice.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.