Dependency Injection with options pattern

此生再无相见时 提交于 2021-02-19 01:36:09

问题


I'm trying to load some settings from the appsettings file and I've got a small issue with the way lists are loaded when using the options pattern. Suppose I've got the following classes (for loading the settings):

public class Application {
    public string Name { get; set; } = "";
    public IEnumerable<string> Roles { get; set; } = new[] {""};
    public Application ToApplicationWithoutPass() => 
        new Application {
            Name = Name,
            Username = Username,
            Roles = Roles.ToList()
        };
}

public class Applications {
    public IEnumerable<Application> AppList { get; set; } = new List<Application>();
}

And here is what the settings that are defined on the appsetings file look like:

"Applications": {
  "AppList": [
    {
      "Name": "SraWebuserAdmin",          
      "Roles": [ "SraEntitiesWriters", "SraEntitiesReaders", "SraEntitiesLoginAccess" ]
    },

...

Here are the entries from the DI setup which is done on the ConfigureServices method:

services.Configure<Applications>(options => Configuration.GetSection("Applications").Bind(options));
services.AddScoped<IApplicationAccessVerifier, ApplicationAccessVerifier>();

And, finally, here's the constructor of the ApplicationAccessVerifier class:

public ApplicationAccessVerifier(IOptionsSnapshot<Applications> applicationOptions) {
  _applicationOptions = applicationOptions;
}

Now, the question: if I don't initialize the AppList property,

public class Applications {
    public IEnumerable<Application> AppList { get; set; }
}

then the settings are loaded correctly.

However, if I initialized it like I've shown (making sure the filed wrapper by the property is initialized with an empty list), then the settings won't be copied to the AppList.

I find this strange since simple properties (ex.: Name on the Application class) aren't affected by the same issue.

Can anyone tell me why this happens or point me to an official documentation about it?

来源:https://stackoverflow.com/questions/59929875/dependency-injection-with-options-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!