开发者

Is there a way to get an ILogger instance inside an extension methods?

开发者 https://www.devze.com 2022-12-07 21:20 出处:网络
I have a static class with extension methods. It used to be a regular class so I took advantage of constructor injection to inject ILogger for logging inside the methods.

I have a static class with extension methods. It used to be a regular class so I took advantage of constructor injection to inject ILogger for logging inside the methods.

After converting the methods to extension methods, I initially added ILogger as a parameter because of the stat开发者_高级运维ic nature of the class.

public static string Overflow(this string message, ..., ILogger logger = null)
{
    ...
    logger?.LogInformation("Stack");
}

But having to pass an instance of ILogger as an argument anytime the extension method is called has become tiring. It should be noted that logging inside these methods is handy but not required therefore, I would want to log only if there is a logger instance registered.

Is there a way to get an instance of ILogger inside the extension methods?

Something like this

public static string Overflow(this string message, ...)
{
    ...
    // Log if there is a registered logger instance available
}


You could . . .

  1. Create an ILogger in your static class using a static constructor, but that might be painful because static constructors cannot take arguments, so you'll have to build the ILogger from scratch.

  2. Create a separate class that has the ILogger you want and write static functions on that class to access the logger. Then call these functions from inside your extension method. We do something similar in the place I call my "day job." We have a static class that has the logger, so we can call MyCompanyLogger.LogInformation(...) from virtually anywhere.

0

精彩评论

暂无评论...
验证码 换一张
取 消