Search code examples
c#dependency-injectionazure-functionsserilog

Serilog implementation broke Options pattern


I am using Azure functions (In-process). I had implementation of options pattern. The options pattern does not work after I had installed packages Microsoft.Extensions.Logging and Serilog.Sinks.ApplicationInsights. That means it is not possible to get any value from config file in service consructor.

Startup:

public override void Configure(IFunctionsHostBuilder builder)
{
        var context = builder.GetContext();
        var config = context.Configuration;
        builder.Services.Configure<MyConfig>(config);
        builder.Services.AddScoped<MyService>();
        
         //only this was added
        builder.Services.AddLogging(loggingBuilder =>
                loggingBuilder.AddSerilog(dispose: true));
}

MyConfig:

public class MyConfig
{
    public string MyProp { get; set; }
}

MyService:

public class MyService
{
        private readonly MyConfig _config;
        private readonly ILogger<MyService> _logger;

        public MyService(IOptions<MyConfig> config, ILogger<MyService> logger)
        {
            _config = config.Value; 
            //config.Value.MyProp = null
            _logger= logger; 
        }
}

Update: It does not register IOptions.


Solution

  • I have resolved it. In the startup the configure should be:

    builder.Services.Configure(config.Bind);