1

Community:

I'm struggling to figure out how to create a single AMQP connection that lives with my ASP.NET application lifecycle in ASP.NET using .NET Core 2.1. After researching, I've found lots of references to using a single AMQP connection for the whole application as they are expensive and slow to create and I was headed down the road of creating the connection using DI but it appears my approach is flawed, I can't seem to identify which interface I need to add as a singleton...

public void ConfigureServices(IServiceCollection services)
        {
            var sqlConnectionStringBuilder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("DefaultConnection"));
            var envSQL = Environment.GetEnvironmentVariable("ASPNETCORE_SQL_SERVER");
            if (envSQL != null)
                sqlConnectionStringBuilder.DataSource = envSQL;

            services.AddSingleton<IMessageBusService, MessageBusService>();
            services.AddSingleton<EasyNetQ.IAdvancedBus, RabbitAdvancedBus>();
            services.AddSingleton<EasyNetQ.IConnectionFactory, ConnectionFactoryWrapper>();

            services.AddMvc();

        }

Adding the above interfaces works but I get an error about ConnectionConfiguration service not being locatable. Is this the right direction or is there a more proper way to create a single application once EasyNetQ connection in ASP.NET core?

jayc
  • 11
  • 3

1 Answers1

0

You can use AutoSubcriber in .net core and use the sample code here.

add connection to appsettings.json

"MessageBroker": {
"ConnectionString": "host=localhost"
}

then add IBus in ConfigureServices

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IBus>(RabbitHutch.CreateBus(Configuration["MessageBroker:ConnectionString"]));
        services.AddSingleton(RabbitHutch.CreateBus(Configuration["MessageBroker:ConnectionString"]));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

add class AppBuilderExtension and use extension method for auto subscriber

public static class AppBuilderExtension
{
    public static IApplicationBuilder UseSubscribe(this IApplicationBuilder appBuilder, string subscriptionIdPrefix, Assembly assembly)
    {
        var services = appBuilder.ApplicationServices.CreateScope().ServiceProvider;

        var lifeTime = services.GetService<IApplicationLifetime>();
        var Bus = services.GetService<IBus>();
        lifeTime.ApplicationStarted.Register(() =>
        {
            var subscriber = new AutoSubscriber(Bus, subscriptionIdPrefix);
            subscriber.Subscribe(assembly);
            subscriber.SubscribeAsync(assembly);
        });

        lifeTime.ApplicationStopped.Register(() => Bus.Dispose());

        return appBuilder;
    }
}

add UseSubscribe in Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseSubscribe("ClientMessageService", Assembly.GetExecutingAssembly());

        app.UseHttpsRedirection();
        app.UseMvc();
    }

then create Producers controller

[Route("api/[controller]")]
[ApiController]
public class ProducersController : ControllerBase
{
    private readonly IBus _bus;

    public ProducersController(IBus bus)
    {
        _bus = bus;
    }
    [HttpGet]
    [Route("Send")]
    public JsonResult Send()
    {

        _bus.Publish(new TextMessage { Text = "Send Message from the Producer" });

        return new JsonResult("");
    }


}

then create Consumers controller

[Route("api/[controller]")]
[ApiController]
public class ConsumersController : ControllerBase, IConsume<TextMessage>
{
    [HttpGet]
    [Route("Receive")]
    public JsonResult Receive()
    {
        using (var bus = RabbitHutch.CreateBus("host=localhost"))
        {
            bus.Subscribe<TextMessage>("test", HandleTextMessage);
        }
        return new JsonResult("");
    }


    private static void HandleTextMessage(TextMessage textMessage)
    {
        var item = textMessage.Text;
    }

    public void Consume(TextMessage message)
    {
        // code receive message
    }
}
Reza Jenabi
  • 3,884
  • 1
  • 29
  • 34