Access objects within a Consumer

2019-08-09 05:51发布

问题:

I am working on a project that consumes messages using MassTransit and RabbitMQ in C#

I'm building a prototype and right now the consumer project is a console application. Within the Main program.cs class, I connect to the bus and subscribe to accept messages from the publisher like this:

var bus = BusInitializer.CreateBus("Subscriber", x =>
            {
                x.Subscribe(subs =>
                {
                    subs.Consumer<UpdatedInformation>().Permanent();
                });
            });

For reference, here's the CreateBus() method:

public static IServiceBus CreateBus(string queueName, Action<ServiceBusConfigurator> moreInitialization)
{
    var bus = ServiceBusFactory.New(x =>
    {
        x.UseRabbitMq();
        x.ReceiveFrom("rabbitmq://localhost/test" + queueName);
        moreInitialization(x);
    });

    return bus;
}

And here is an example of one of the consumer classes:

class UpdatedInformationConsumer : Consumes<UpdatedInformation>.Context
{

    public void Consume(IConsumeContext<UpdatedInformation> message)
    {
        Console.Write("\nMessage: " + message.Message);
        Console.Write("\nPROCESSED: " + DateTime.Now.ToString());
    }
}

In the main class of the subscriber, I also initialize services and other configurations. What I need to do is be able to access those services/objects in my consumer classes as I don't want to initialize new ones every time a message is received in consumed.

This should be relatively easy, but I'm stumped since I'm not actually creating instances of my consumer classes.

回答1:

Rather than put a bunch of singletons in your service, which leads to a bunch of static methods and so forth, you can specify a consumer factory with your subscription that passes those dependencies to your consumer. You can also use any of the supported containers (or even your own) to resolve those dependencies.

x.Subscribe<UpdatedInformationConsumer>(() => 
    new UpdatedInformationConsumer(dependency1, dependency2, etc));

A new instance of the consumer will be created for each message receiving, so object lifecycles can also be managed in this way.