In an ASP net core project, the built-in DI container was replaced by Autofac. I use the ConfigureContainer method to register dependencies through modules. If the module needs settings, it gets them through IConfiguration (from the json file).

Everything was fine until it was necessary to register services that are fully described in the settings. For example:

"Serials": [ { "Port": "COM1", "BaudRate": 9600 }, { "Port": "COM2", "BaudRate": 9600 } ] 

So in the DI container, 2 ports should be registered as IEnumerable<SerialPorts> . For this task, you need a typed view of settings, which is provided through IOptions<T>

  public void ConfigureServices(IServiceCollection services) { .... services.Configure<SerialPortsOption>(AppConfiguration); } 

Those. A Key-Value pair is taken from AppConfiguration and a SerialPortsOption object is constructed from them. After it is built by the AUTOMATIC, it is registered in DI and access to it is possible through the IOptions<SerialPortsOption> on the container.

The problem is that I need a IOptions<SerialPortsOption > before Build is made on the container, which of course is not possible. Is it possible to reach the settings of IOptions<T> before the container build?

  public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddTransient<IConfiguration>(provider=> AppConfiguration); services.AddMvc().AddControllersAsServices(); services.AddOptions(); services.Configure<SerialPortsOption>(AppConfiguration); //СОЗДАНИЕ DI КОНТЕЙНЕРА var builder = new ContainerBuilder(); builder.Populate(services); ConfigureContainer(builder); ApplicationContainer = builder.Build(); return new AutofacServiceProvider(this.ApplicationContainer); } public void ConfigureContainer(ContainerBuilder builder) { var spOptions= container.Resolve<IOptions<SerialPortsOption>>().Value; //!!!!! нужно получить настройки builder.RegisterModule(new SerialPortAutofacModule(spOptions)); } 
  • And what prevents them from getting them from AppConfiguration? .. - Pavel Mayorov
  • I understand from AppConfiguration you need to pull out all the settings manually through key access, then create an object representation of the settings for these values. It seems to me then it is easier to deserialize from JSON manually. - Aldmi
  • For example, I gave the setting of the last. A port that contains few properties and nesting settings. Manually this is not an easy way to disassemble everything, as it seems to me. Just there is a good tool, and it will not be used) - Aldmi

0