0

I created the following class:

public static class PingEndpoints
{
    public static void Endpoints(this WebApplication application)
    {
        var group = application.MapGroup("ping");

        group.MapGet("", PingMethod);
    }

    internal static IResult PingMethod([FromServices] ILogger<PingEndpoints> logger)
    {
        try
        {
            logger.LogInformation("Test log");
            var pingInfo = new PingInfo(DateTime.UtcNow, "Ping successfull");
            return Results.Ok(pingInfo);
        }
        catch (Exception ex)
        {

            //wanted to log error
        }
    }
}

Above class is registered in the program.cs like below:

var builder = WebApplication.CreateBuilder(args);

...

var app = builder.Build();

...

app.Endpoints();

app.Run();

Fyi, I can inject any dependency into the PingMethod as a parameter.

Now, In the above class compiler gives me an error (i.e static types can not be used as type arguments) while injecting an instance of logger into the PingMethod method.

Can anyone suggest how can I inject Logger with the same class which I am using Here, I am creating many other endpoints as well.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Hardipsinh Jadeja
  • 1,180
  • 1
  • 13
  • 30

1 Answers1

2

You can use any non-static class:

public static class PingEndpoints
{
    internal static IResult PingMethod([FromServices] ILogger<PingInfo> logger)
    {
        // ...
    }
}

Or inject logger factory and create logger from it:

public static class PingEndpoints
{
    internal static IResult PingMethod([FromServices] ILoggerFactory loggerFactory)
    {
        var logger = loggerFactory.CreateLogger(nameof(PingEndpoints));
        // or to match the generic logger approach:
         var logger = loggerFactory.CreateLogger("PingEndpointsNamespace.PingEndpoints"));
        // ...
    }
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • I like your solution but am worrying about how can I mock it in Unit test cases using xUnit – Hardipsinh Jadeja Apr 06 '23 at 06:48
  • @HardipsinhJadeja it would be a bit harder but not that much (one more step - instead of setting up logger you will set up factory which will return the set up logger). Also you can use [`NullLoggerFactory`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.abstractions.nullloggerfactory?view=dotnet-plat-ext-7.0) in case you don't want actually test it. – Guru Stron Apr 06 '23 at 07:06