Reputation: 4024
I want to add a method to the existing LoggerExtensions on Core 2.1 that will need to use IConfiguration to read some settings from the appsettings.json file.
I created a partial static class with my new method inside it but this does not allow me to access the IConfiguration as it is a static class.
How could I create this new method that is part of LoggerExtensions that can read from IConfiguration?
In the example below I can't access _configuration.GetSection as I can not inject it
public static partial class LoggerExtensions
{
public static void EmailError(this ILogger logger, Exception exception, string message)
{
using (var smtpClient = new SmtpClient(config.GetSection("Host").Value))
{
// ......
}
}
}
Upvotes: 2
Views: 1549
Reputation: 46501
You should add the IConfiguration
instance as a parameter to the extension method. For example:
public static void LogErrorAndEmail(this ILogger logger, IConfiguration configuration, Exception exception, string message, params object[] args)
{
// ...
}
A better option might be to create a custom logger implementation which sends a mail under specific conditions. You can start by implementing the ILogger
interface and implement your mail logic in the Log
method. Inject the IConfiguration
instance in the constructor. Secondly create a ILoggerFactory
implementation to create a new instance of your custom logger, inject the IConfigruation
parameter in the constructor as well and pass it to your logger. Finally call services.AddSingleton<ILoggerProvider, YourCustomLoggerProvider>()
in the startup class to register your custom logger.
Upvotes: 3