Search code examples
functionazureloggingcode-injection

Example on how to wire up durable function dependency injection


Having successfully created and run a simple Azure Durable Function in Visual Studio 2017, I want to introduce logging.

The Visual Studio project template generates the static HttpStart class with a Run method containing an optional parameter of type Microsoft.Extensions.Logging.ILogger.

I have no idea how to hook up dependency injection into a durable function project. Can anyone point me to an example on how to achieve this?

It looks to me like I will need some class, inside which I will need to use the Microsoft.Extensions.Logging.LoggingFactory.CreateLogger() method.

I imagine that this logic will need to be within a container class that is hooked into the run time pipeline using HostBuilder in some way (similar to using WebHostBuilder in static main method).

Thank you


Solution

  • @Thomas pointed me to examples I used to extract code that allows dependency injection to work when writing a durable function project:

    using System.IO;
    using System.Reflection;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using NLog;
    using NLog.Extensions.Logging;
    using tmetadastoreFnApp;
    using Willezone.Azure.WebJobs.Extensions.DependencyInjection;
    using ILogger = Microsoft.Extensions.Logging.ILogger;
    using LogLevel = Microsoft.Extensions.Logging.LogLevel;
    
    [assembly: WebJobsStartup(typeof(Startup))]
    namespace tmetadastoreFnApp
    {
        internal class Startup : IWebJobsStartup
        {
            public void Configure(IWebJobsBuilder builder) =>
                builder.AddDependencyInjection(ConfigureServices);
    
            private void ConfigureServices(IServiceCollection services)
            {
    
                services.AddSingleton<ILoggerFactory, LoggerFactory>();
                services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
                services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
    
                var serviceProvider = services.BuildServiceProvider();
    
                var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
                loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
    
                var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                LogManager.LoadConfiguration(Directory.GetParent(dir) + "\\nlog.config");
    
            }
        }
    }