stevejgordon / CorrelationId

An ASP.NET Core middleware component which synchronises a correlation ID for cross API request logging.
MIT License
560 stars 106 forks source link

Can't inject "CorrelationIdsTransient" into custom middleware. #10

Closed AlonCG closed 6 years ago

AlonCG commented 6 years ago

Hello, sorry for this question, I am a bit at wits end. First, thanks for this code, I think it is exactly what I need. However, I can not figure out how to register the Transient class to be injected into my custom middleware. If I use an actionFilter, then it works fine, but for some reason I can't get it injected properly otherwise in the middleware.

ConfigServices is defined with ...

services.AddCorrelationId();
services.AddTransient<CorrelationIdsTransient>();
services.AddTransient<LogAsyncActionsFilter>();
services.AddMvc(options => {
        options.Filters.Add(typeof(LogAsyncActionsFilter));
    }).AddJsonOptions(options => {
        options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        options.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore; 
    }
);

Configure has ...

app.UseCorrelationId(new CorrelationIdOptions() { 
    Header = "X-Etrs-Correlation-ID", 
    IncludeInResponse = true }
); //2nd line

app.UseActionLog(); //no matter where this is, the correlation id is not injected into the middleware

This is my first attempt at middleware and any suggestions would be appreciative...

(Sorry, I think the formatting here is shotty!)

AlonCG commented 6 years ago

So I think this is actually a stupid issue, i can just access the trace identifier from the HttpContext in the middleware. So ... unless that is not what I should be doing, please let me know. Thanks!

stevejgordon commented 6 years ago

@AlonCG Sorry I missed the notification on this one. Inside middleware it's safe to simply use the HttpContext directly as you suggest.

AlonCG commented 6 years ago

@stevejgordon Awesome no worries, thanks!