Create a middleware to add metadata to all outgoing DAPR messages

42 Views Asked by At

I would like to add a correlationId as metadata to all my outgoing DAPR messages in C#. I have created a middleware that I get CorrelationId from every time and then assign it to all outgoing Http requests, however I am unable to set correlationId to all outgoing DAPR messages. Can anyone help?

This is my CorrelationId middleware's invoke method

public async Task InvokeAsync(HttpContext context, ICorrelationIdGenerator correlationIdGenerator)
{
     var correlationId = correlationIdGenerator.Get() == null
                         ? Guid.NewGuid.ToString()
                         : correlationIdGenerator.Get();
     correlationIdGenerator.Set(correlationId);
     if (!context.Request.Headers.ContainsKey(Http.Headers.CORRELATION_ID))
     {
        context.Request.Headers.Add(Http.Headers.CORRELATION_ID, correlationId);
     }

     context.Response.OnStarting(() =>
     {
        if (!context.Response.Headers.ContainsKey(Http.Headers.CORRELATION_ID))
        {
            context.Response.Headers.Add(Http.Headers.CORRELATION_ID, correlationId);
        }
        return Task.CompletedTask;
     });
    await next(context);
}

and this is how everything is registered:

Services.AddScoped<ICorrelationIdGenerator, CorrelationIdGenerator>();
Services.AddDaprClient();

DaprClient is registered as Singleton when i look at the implementation. At the moment I call correlationIdGenerator everytime I invoke Dapr's PublishEventAsync like so:

private readonly DaprClient _client;
private readonly ICorrelationIdGenerator _cid;
public MyClass(DaprClient client, ICorrelationIdGenerator cid)
{
    _client = client;
    _cid = cid;
}

var correlationId = _cid.Get();

var metadata = new Dictionary<string, string>
{
    { Http.Headers.CORRELATION_ID, correlationId }
};

await _client.PublishEventAsync("component", "my-topic", data, metadata: metadata);

So my goal is to inject metadata to all PublishEventAsync methods so I don't have to pass in the metadata for every call. Is this possible? How can I achieve this?

I am using Dapr.AspNetCore v1.11.0 and Dapr.Workflow v1.11.0.

0

There are 0 best solutions below