Publishing
Basic Publishing
To publish the message you just need an instance of IPublisher (or derived interfaces if using Silverback.Core.Model, as shown later on).
using Silverback.Messaging.Publishing;
public class PublishingService
{
private readonly IPublisher _publisher;
public PublishingService(IPublisher publisher)
{
_publisher = publisher;
}
public async Task PublishSomething()
{
await _publisher.PublishAsync(new SampleMessage
{
Content = "whatever"
});
}
}
The publisher always exposes a synchronous and an asynchronous version of each method. The second option is of course to be preferred to take advantage of non-blocking async/await.
Return values
In some cases you will of course return a response after having processed the message.
public async Task<Report> PublishSomething()
{
var result = await _publisher.PublishAsync(new ReportQuery() { ... });
return result.Single();
}
Important
Please note the required call to Single()
, because Silverback allows you to have multiple subscribers for the same message and therefore collect multiple return values. This is not needed if using IQueryPublisher or ICommandPublisher described in the Creating the Message model page.
Silverback.Core.Model
Silverback.Core.Model has been introduced in the previous page Creating the Message model.
Each message type (IEvent, ICommand/ICommand<TResult> and IQuery<TResult>) also comes with its specialized IPublisher as quickly shown in the following sub-chapters.
Events
The messages implementing IEvent, IDomainEvent or IIntegrationEvent can be published using an IEventPublisher.
using Silverback.Messaging.Publishing;
public class PublishingService
{
private readonly IEventPublisher _publisher;
public PublishingService(IEventPublisher publisher)
{
_publisher = publisher;
}
public async Task PublishEvent()
{
var myEvent = new MyEvent() { ... };
await _publisher.PublishAsync(myEvent);
}
}
Commands
The messages that implement ICommand, ICommand<TResult> or IIntegrationCommand can be published using an ICommandPublisher.
using Silverback.Messaging.Publishing;
public class PublishingService
{
private readonly ICommandPublisher _publisher;
public PublishingService(ICommandPublisher publisher)
{
_publisher = publisher;
}
public async Task ExecuteCommand()
{
var command = new MyCommand() { ... };
await _publisher.ExecuteAsync(command);
}
}
Queries
The IQueryPublisher ca be used to publish the messages implementing the IQuery<TResult> interface.
using Silverback.Messaging.Publishing;
public class PublishingService
{
private readonly IQueryPublisher _publisher;
public PublishingService(IQueryPublisher publisher)
{
_publisher = publisher;
}
public async Task<MyResult> GetResults()
{
var query = new MyQuery() { ... };
var result = await _publisher.ExecuteAsync(myQuery);
return result;
}
}