Search code examples
c#asp.net-coredependency-injectionconfigurationazure-webjobs

Passing configuration to webjobs via dependency injection


This question is based on comments associated with this answer.

To summarize, the question is how to pass configuration settings to a web job without injecting the IConfiguration interface as a dependency when calling ConfigureServices to set up dependencies.

I had thought this would be a good way to do it:

IHostBuilder builder = new HostBuilder;

...

builder.ConfigureServices((context, services) =>
{
    services.AddSingleton<IMyModelClass, MyModelClass>(sp => new MyModelClass(context.Configuration));
    services.AddSingleton<IMyServiceClass, MyServiceClass>(sp => new MyServiceClass(new MyModelClass()));
})

Here, MyModelClass is a class that reads the configuration settings, like this:

public class MyModelClass : IMyModelClass
{
    public string MySetting { get; set; }

    public MyModelClass(IConfiguration config)
    {
        this.MySetting = config["MySetting"];
    }
}

It thus encapsulates those settings and can be passed to other classes (like MyServiceClass) that need to access the configuration settings.

But it seems this isn't the best way. Any further suggestions?


Solution

  • So lets assume there is the following configuration

    {
      "MyModelSection": {
        "MySetting": "SomeValue"
      }
    }
    

    This is just a very simple example.

    The associated model would look like

    public class MyModelClass: IMyModelClass {
        public string MySetting { get; set;}
    }
    

    The above can be extracted from configuration and registered with services

    builder.ConfigureServices((context, services) => {
        var configuration = context.Configuration.
    
        var myModel = configuration.GetSection("MyModelSection").Get<MyModelClass>();
    
        services.AddSingleton<IMyModelClass, MyModelClass>(myModel);
    
        services.AddSingleton<IMyServiceClass, MyServiceClass>();
    })