5

I familiar with Middleware concept and I had implemented many Middlewares on my project. And also I read ASP.NET Core Middleware documentation at Microsoft docs. But this time I faced with confusing problem, Actually I wrote a simple middle to write logs per each requests.

This is my middleware class:

public class LoggerMiddleware
{
    private readonly RequestDelegate _next;

    public LoggerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext, LogDbContext dbContext)
    {
        var logInfo = await Logger.InitiateLogging(httpContext, dbContext);
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            await Logger.AddException(httpContext, ex, true);
        }
        finally
        {
            await Logger.PersistLog(logInfo, httpContext);
        }
    }
}

Then I declared an extension-method:

public static class LoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseLogger(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<LoggerMiddleware>();
    }
}

And finally I called UseLogger method on Configure on Startup.cs.

This is my startup.cs code:

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory,
    IServiceScopeFactory scopeFactory,
    IOptions<BaranSettings> baranSettings)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();


    // other lines of code...
    app.UseLogger();
    // other lines of code...
}

Problem:

The problem is LoggerMiddleware constructor called, but the Invoke method doesn't call. Does any one know what is the problem?

piet.t
  • 11,718
  • 21
  • 43
  • 52
Siavash
  • 2,813
  • 4
  • 29
  • 42

1 Answers1

4

For this particular use case, I would strongly urge you to consider using .Net Core DI and inject an ILoggerFactory:

Why ASP.NET Core DI knows how to resolve ILogger<T>, but not ILogger?

See also:

How to Use LoggerFactory and Microsoft.Extensions.Logging for .NET Core Logging With C#

paulsm4
  • 114,292
  • 17
  • 138
  • 190