简体   繁体   中英

Unable to DI custom object in Azure Function App Startup

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "tester": "e=e",
    "ProjectConfiguration": "{\"tester\": \"tes22\"}"
  }
}

Startup.cs

    class Startup : FunctionsStartup
    {

        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddOptions<ProjectConfiguration>()
                .Configure<IConfiguration>((option, configuration) =>
                {
                    System.Diagnostics.Debug.WriteLine($"hello:{configuration.GetSection("ProjectConfiguration").Value}");
                    configuration.GetSection("ProjectConfiguration").Bind(option);
                });
        }
    }

I am able to print out hello:{"tester": "tes22"} but when I try to access it in another class, it is null.

    public class InitFunction
    {
        private readonly ProjectConfiguration _projectConfiguration;

        public InitFunction(Microsoft.Extensions.Options.IOptions<ProjectConfiguration> options)
        {
            _projectConfiguration = options.Value;
            System.Diagnostics.Debug.WriteLine(JsonConvert.SerializeObject(options.Value));
        }

option.value printed out is {"tester":null}

It seems like .bind is not binding the object properly. How can I do this? Thank you!

You need to provide the ProjectConfiguration properties as : delimited keys.

Assuming you have a configuration class like this:

class ProjectConfiguration {
    public string Title { get; set; }
    public int ANumber { get; set; }
}

Its JSON equivalent would be:

{
  "IsEncrypted": false,
  "Values": {
    // ...
    "ProjectConfiguration:Title": "My App",
    "ProjectConfiguration:ANumber": 123
  }
}

References:

https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#working-with-options-and-settings

Apart from @abdusco's answer, if you do not want : -delimited keys, you could bind your ProjectConfiguration directly to the "Values" section of local.settings.config

{
    "IsEncrypted": false,
    "Values": {
        // ...
        "Tester": "tes22"
    }
}
public class ProjectConfiguration
{
    public string Tester { get; set; }
}
builder.Services
  .AddOptions<ProjectConfiguration>()
  .Configure<IConfiguration>((pc, config) => config.Bind(pc));

Theoretically the Bind method also has an overload to specify a key, presumably to use custom sections in the config but I was not able to get it to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM