Search code examples
asp.net-core-2.0nlogloggerfactory

ASP.NET Core - StartUp class and Dependency Injection with ILoggerFactory


I'm using ASP.NET Core 2.1 and NLog. If I add a constructor in StartUp that has a dependency on ILoggerFactory it resolves it to a different instance than the one I get in Configure method. In Configure method I call AddNLog and because it's a different instance, the instance I used in ConfigureServices is not ready for NLog.

Any ideas how can I access ILoggerFactory in ConfigureService and have the same instance in Configure so I can call AddNLog? Calling AddNLog in ConfigureServices doesn't work.


Solution

  • I solved it by registering some code in the application started event.

    In Configure method:

                appLifetime.ApplicationStarted.Register(() =>
                {
                    InitializeSingletonObjects(app, loggerFactory);
                });
    

    At that point everything is initialized correctly and you can do whatever you want in InitializeSingletonObjects. In my case, this is what I did.

            private void InitializeSingletonObjects(IApplicationBuilder app, ILoggerFactory loggerFactory)
            {
                // email template processor
                var emailRepository = app.ApplicationServices.GetService<IEmailRepository>();
                IEmailTemplateProcessor emailTemplateProcessor = app.ApplicationServices.GetService<IEmailTemplateProcessor>();
                string containerName = appConfiguration.AzureBlobStorage.BlobStorageContainerEmailTemplates;
                var emailTemplates = emailRepository.GetEmailTemplates(true);
    
                emailTemplateProcessor.Initialize(containerName, emailTemplates);
            }
    

    More info about IApplicationLifetime on https://www.khalidabuhakmeh.com/looking-at-asp-net-cores-iapplicationlifetime