0

I'm trying to put together a 'generic' subscriber that I can (re)use with Azure ServiceBus.

But I'm stuck as follows; my code once stripped of non essential parts looks like this.

Subscribing.Client.OnMessage((recdMessage =>
{
    var msgBody = recdMessage.GetBody<myClass>();
}, options);

I want my msgBody to be of the type that has been serialised into the body of the message. Indeed if myClass were to be something like TelephonyEventMessage and the message received was of that type then my msgBody would be a correctly instantiated/rehydrated object of that type. But although I can use recdMessage. ContentType to get the string name of the class in that message.... I just cant figure what I need to put in myClass above. I'm at the end of my knowledge now and no amount of searches seems to look like an answer for me. Do I need to add a specific version for every type that may exist in my messages?

0

1 Answer 1

1

You can use this to receive messages from a subscription if you are expecting a number of different object types:

public void ReceiveMessageFromSubscription<T>(string topicPath, string subscriptionName, Action<T> action)
{
    var client = SubscriptionClient.CreateFromConnectionString(ConnectionString, topicPath, subscriptionName);

    client.OnMessage((message) =>
    {
        try
        {
            _logger.Information("Processing message");
            action(message.GetBody<T>());
            message.Complete();
        }
        catch(Exception ex)
        {
            _logger.Error(ex, "Error processing message");
            message.Abandon();
        }
    } );
}

And then pass in a method which knows how to handle the object, as below. You could have a number of these methods, all calling ReceiveMessageFromSubscription.

public void ProcessObject()
{
    _serviceBusService.ReceiveMessageFromSubscription<MyObject>(mytopic, mysubscription, _myobjectService.ProcessObject);
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.