3

I've got an asp.net core app and this is my set-up:

services.AddSingleton(typeof(ISchedule), typeof(MySchedule));
services.AddLogging();
services.AddScheduler((sender, args) =>
{
    // How do I log here?
});

Unfortunately I don't have control over that scheduler middleware, so that AddScheduler and the lambda is all I have.

So far the only thing I have managed to come up with is:

services.AddSingleton(typeof(ISchedule), typeof(MySchedule));
services.AddLogging();

IServiceProvider serviceProvider = services.BuildServiceProvider();
services.AddScheduler((sender, args) =>
{
    ILogger<ISchedule> logger = serviceProvider.GetService<ILogger<ISchedule>>();
    logger.LogError(args.Exception, "Uncaught exception during processing");
    args.SetObserved();
});

But this is just another way to sneak in a kind of "ServiceLocator", via the closure.

Are there any better ideas? How should this be ideally handled?

(Re this is not a duplication of How do I write logs from within Startup.cs because this is about injecting into an event handler, not in the startup object.)

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Volker
  • 1,753
  • 2
  • 18
  • 28
  • 1
    Possible duplicate of [How do I write logs from within Startup.cs](https://stackoverflow.com/questions/41287648/how-do-i-write-logs-from-within-startup-cs) – Felix K. Oct 15 '18 at 20:15
  • You could inject an `ILoggerFactory` in the Startup constructor so it becomes available in ConfigureServices. – Felix K. Oct 15 '18 at 20:16

0 Answers0