Skip to content

Subscribe to events

How to subscribe to platform events

The IEventSubscriberClient is the entry point for event subscription management. The service can be constructed manually, but it can be resolved from DI container (after using AddPlatformClients extension).

var collection = new ServiceCollection();
collection.AddPlatformClients(o =>
{
    o.ConfigureOpenApiKey(openapikey);
    o.PlatformEnvironment = PlatformEnvironment.Dev;
});
using var provider = collection.BuildServiceProvider();
var eventSubscriber = provider.GetRequiredService<IEventSubscriberClient>();

During the development and stabilization phase, it is recommended to add logging service and to configure its level to debugging. IEventSubscriberClient will log connectionId, subscriptionId are other relevant information that is usefull during troubleshooting.

Subscribe to project events

IEventSubscriberClient provides capability to subscribe to project events.

The example below subscribes to project events and provides a message handler. In the case of example that is implemented in a console application, the message handler outputs message data into console.

using var subscription = await eventSubscriber.SubscribeAsync(projectId, (message) =>
{
    Console.WriteLine(message.ProjectId + " " + message.Data);
    return Task.CompletedTask;
}, cancellationToken);

During the subscribe hand-shake between client and server, the message offset is provided. The offset indicates the last message received by the client. IEventSubscriberClient will ensure that message offset is stored locally during application shut-down by using default implementation of IMessageOffsetProvider, and message offset will be loaded on next application start-up. In case of initial connection, IEventSubscriberClient will connect without providing an offset. Custom implementation of IMessageOffsetProvider can be injected into IEventSubscriberClient.