Question

I'm building an API with ServiceStack. I'd like each request to have a unique ID so that I can trace it through the system (which is distributed).

I have my contracts assembly containing my API's DTOs, and so I thought the natural place would be to make each Request derive from a base class that had a sealed protected parameterless constructor that assigned a new ID (probably a GUID is fine).

However, it'll be possible to use my API via the clients without necessarily using the contract DTOs assembly - naked, if you will. At that point, the clients can assign whatever IDs they like (since the property will be a string to be accomodating, and I want ID assignment to be quick).

So, this leads me to think that the service should assign request IDs when the requests arrive at the system. So - I'm currently thinking that the best thing to do is have an ID property on each request DTO that is validated to be empty by the API - clients cannot set it. Then, a before-everything filter to assign a value to the DTO property.

Is that sensible?

Is there a more elegant way to do it (that still works against naked clients?)?

Was it helpful?

Solution

Using a global request filter would work, you can do something like:

public class IRequiresUniqueId
{
    public Guid UniqueId { get; set; }
}

And then mark all request DTOs you would like to have a Unique Id by implementing the above interface:

public MyRequest : IRequiresUniqueId
{
    public Guid UniqueId { get; set; }
}

Then you can use a Global Request Filter to set all request DTOs that have them:

this.RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
     var requiresUniqueId = requestDto as IRequiresUniqueId;
     requiresUniqueId.UniqueId = Guid.NewGuid();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top