Skip to content

Instantly share code, notes, and snippets.

@hallidev
Created December 5, 2019 15:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hallidev/300c50fa1bab3a44c3ee2fcb45c6eb1e to your computer and use it in GitHub Desktop.
Save hallidev/300c50fa1bab3a44c3ee2fcb45c6eb1e to your computer and use it in GitHub Desktop.
Emit MediatR Events to EventGrid
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MyApp.AppServices.Configuration;
using MyApp.AppServices.EventBus.Command;
using MyApp.AppServices.Model.EventGrid;
using Framework.EventBus.Command;
using Framework.Model;
using MediatR;
using Microsoft.Azure.EventGrid;
using Microsoft.Azure.EventGrid.Models;
namespace MyApp.AppServices.EventBus.PipelineBehaviors
{
/// <summary>
/// Post-response logic for emitting events to event grid
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
internal class EmitEventPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private const string EventTypeFormat = "MyApp.{0}";
private const string EventSubjectFormat = "AppServices/{0}";
private const string EventDataVersion = "1.0";
private readonly EventGridClient _eventGridClient;
private readonly EventGridConfig _eventGridConfig;
public EmitEventPipelineBehavior(EventGridClient eventGridClient,
EventGridConfig eventGridConfig)
{
_eventGridClient = eventGridClient;
_eventGridConfig = eventGridConfig;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
RequestHandlerDelegate<TResponse> next)
{
var response = await next();
// Emit event to EventGrid
if (response is CommandResult<CommandEventData> commandResult
&& commandResult.Outcome == Outcome.Success
&& commandResult.EventList != null
&& commandResult.EventList.Count > 0)
{
var eventGridEvents = ToEventGridEventList(commandResult.EventList);
// For Azure Function development using Postman
// var eventsJson = eventGridEvents.ToJson();
// Fire and forget - results are discarded
_ = _eventGridClient.PublishEventsAsync(_eventGridConfig.TopicHostname, eventGridEvents, cancellationToken);
}
return response;
}
private List<EventGridEvent> ToEventGridEventList(List<CommandEventData> eventList)
{
return eventList
.Select(eventData =>
new EventGridEvent
{
Id = Guid.NewGuid().ToString(),
Data = new EventGridEventData
{
UserSecurityInfo = eventData.UserSecurityInfo,
EventType = eventData.EventType,
Target = eventData.Target,
Context = eventData.Context
},
DataVersion = EventDataVersion,
EventTime = eventData.EventTimeUtc,
EventType = string.Format(EventTypeFormat, eventData.EventType.ToString()),
Subject = string.Format(EventSubjectFormat, eventData.Source)
}).ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment