CorrelationId Documentation

repository·main·Indexed 20 days ago

https://github.com/stevejgordon/correlationid

A lightweight .NET Standard 2.0+ library for distributed applications to trace requests across multiple services. It manages and propagates correlation IDs via request headers and Correlation Context, providing ICorrelationIdProvider implementations like GuidCorrelationIdProvider and TraceIdCorrelationIdProvider, and an ICorrelationContextAccessor for accessing IDs in business logic or background services.

Tokens
2.2K
Snippets
8
Records
11
Agent score
69%

What's inside CorrelationId

  1. What is Correlation ID?

    main
    The Correlation ID library is a lightweight solution for managing request correlation. It allows you to parse a configurable correlation ID header from incoming HTTP requests, access that ID within your application code, and optionally include it in outgoing requests to maintain traceability across distributed systems.
  2. How ICorrelationIdProvider works

    main

    In version 3.0.0 and later, the library uses the ICorrelationIdProvider abstraction to define how correlation IDs are generated. You can choose between different implementations to control the ID generation logic.

    Two built-in implementations are available:

    • GuidCorrelationIdProvider: Generates new GUID-based correlation IDs.
    • TraceIdCorrelationIdProvider: Sets the correlation ID to the same value as the HttpContext.TraceIdentifier.

    Important: Only one provider may be registered. Registering multiple providers will throw an InvalidOperationException.

    // Example of registering a specific provider using the generic AddCorrelationId method
    services.AddCorrelationId<TraceIdCorrelationIdProvider>();
  3. Access CorrelationId via ICorrelationContextAccessor

    main

    Since version 2.0.0, the library uses a CorrelationContext to allow access to the Correlation ID in classes that do not have direct access to HttpContext (such as background services or deep business logic layers).

    You can inject ICorrelationContextAccessor into your classes to retrieve the current CorrelationContext and its associated ID.

    public class MyService
    {
        private readonly ICorrelationContextAccessor _correlationContextAccessor;
    
        public MyService(ICorrelationContextAccessor correlationContextAccessor)
        {
            _correlationContextAccessor = correlationContextAccessor;
        }
    
        public void DoWork()
        {
            var correlationId = _correlationContextAccessor.CorrelationContext.CorrelationId;
            // Use the ID...
        }
    }
  4. Register CorrelationId services in ASP.NET Core

    main

    Starting with version 3.0.0, you must register correlation ID services in your IServiceCollection before adding the middleware to the pipeline. There are three ways to register services:

    1. Using AddCorrelationId(): Returns an ICorrelationIdBuilder. This method does not set a default provider, so you must call a builder method (like those for specific providers) to configure which provider to use.
    2. Using AddCorrelationId<T>(): Accepts a type T that implements ICorrelationIdProvider to specify the provider directly.
    3. Using AddDefaultCorrelationId(): Returns the IServiceCollection and uses GuidCorrelationIdProvider as the default. This is useful for chaining extension methods when the default GUID behavior is sufficient.
    // Option 1: Using the builder to configure a provider
    services.AddCorrelationId()
            .UseTraceIdCorrelationIdProvider();
    
    // Option 2: Specifying the provider type directly
    services.AddCorrelationId<GuidCorrelationIdProvider>();
    
    // Option 3: Using the default (GuidCorrelationIdProvider)
    services.AddDefaultCorrelationId();
  5. Configure CorrelationId with Dependency Injection

    main

    To enable the library, register the correlation ID services within your ConfigureServices method. Using AddDefaultCorrelationId registers a correlation ID provider that generates new IDs based on a random GUID.

    services.AddDefaultCorrelationId
  6. Add CorrelationId Middleware to the Pipeline

    main

    Register the correlation ID middleware in your application pipeline using app.UseCorrelationId(). This should be registered early in the pipeline, before any downstream middleware that requires access to the correlation ID.

    app.UseCorrelationId();
  7. Configure CorrelationIdOptions

    main

    In version 3.0.0 and later, CorrelationIdOptions should be configured via Action delegates on the IServiceCollection extension methods, rather than passing an options instance to UseCorrelationId in the middleware pipeline.

    Common configuration options include:

    • CorrelationIdGenerator: A Func<string> used to customize ID generation if no ID is found in the request header. Note that if this is set, it is used instead of the registered ICorrelationIdProvider.
    • RequestHeader: The name of the header to read the correlation ID from (formerly DefaultHeader).
    • ResponseHeader: The name of the header to which the Correlation ID is written. Defaults to the same value as RequestHeader.
    • IgnoreRequestHeader: If true, the incoming correlation ID in the RequestHeader is ignored and a new one is generated.
    • EnforceHeader: If true, a missing correlation ID header results in a 400 Bad Request response.
    • AddToLoggingScope: If true, the correlation ID is added to the logger scope payload.
    • LoggingScopeKey: The key used in the logger scope (defaults to 'CorrelationId').
    • UpdateTraceIdentifier: Controls whether the ASP.NET Core TraceIdentifier is updated to match the CorrelationId (default is true).
    services.AddDefaultCorrelationId(options =>
    {
        options.CorrelationIdGenerator = () => "Foo";
        options.AddToLoggingScope = true;
        options.EnforceHeader = true;
        options.IgnoreRequestHeader = false;
        options.IncludeInResponse = true;
        options.RequestHeader = "My-Custom-Correlation-Id";
        options.ResponseHeader = "X-Correlation-Id";
        options.UpdateTraceIdentifier = false;
    });
  8. Workaround for ASP.NET Core 2.2.0 TraceIdentifier regression

    main
    In ASP.NET Core 2.2.0, setting the TraceIdentifier on the context via middleware can cause the context to become null later in the pipeline. If you are using this version, you can work around this by disabling the behavior of updating the TraceIdentifier via the options when adding the middleware.
  9. Access the current Correlation ID using ICorrelationContextAccessor

    main

    To retrieve the current correlation ID (for example, for logging purposes), inject the ICorrelationContextAccessor into your class via constructor injection.

    public class TransientClass
    {
       private readonly ICorrelationContextAccessor _correlationContext;
    
       public TransientClass(ICorrelationContextAccessor correlationContext)
       {
    	  _correlationContext = correlationContext;
       }
    
       // Use _correlationContext to access the ID
    }
  10. Reference: CorrelationIdOptions properties

    main

    The following properties are available on CorrelationIdOptions (as of v3.0.1):

    PropertyTypeDescription
    CorrelationIdGeneratorFunc<string>Custom generator used if no ID is found in the request header. Overrides ICorrelationIdProvider.
    RequestHeaderstringThe header name to read the ID from. (Renamed from DefaultHeader).
    ResponseHeaderstringThe header name to write the ID to. Defaults to RequestHeader.
    IgnoreRequestHeaderboolIf true, ignores incoming header and generates a new ID.
    EnforceHeaderboolIf true, returns 400 Bad Request if the header is missing.
    AddToLoggingScopeboolIf true, adds the ID to the logger scope.
    LoggingScopeKeystringThe key used in the logger scope. Defaults to 'CorrelationId'.
    UpdateTraceIdentifierboolIf true, sets ASP.NET Core TraceIdentifier to match the CorrelationId. Defaults to true.