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

1.4k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

1
On

I am not sure if I understood the problem, but can't you just do as explained here:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    //...
    loggerFactory.AddLog4Net(); // << Add this line