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 . . .
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.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.
精彩评论