IOptions doesn’t load settings from json

This is my appsettings.json file:

{
  {
  "User": {
      "Name": "Marco",
      "Level": "developer",
      "Password": "54321"
  },
  "Robot": {
    "Ip": "192.168.2.244",
    "Port": "3111"
  },
  "PLC": {
    "Ip": "192.168.1.1",
    "Port": "5000"
  }
}

Then in my code I wrote a class MyAppSettings:

namespace IOptions_test
{
    public class MyAppSettings
    {
        public UserSettings User { get; set; }
        public RobotSettings Robot { get; set; }
        public PlcSettings PLC { get; set; }
    }

    public class UserSettings
    {
        public string Name { get; set; }
        public string Level { get; set; }
        public string Password { get; set; }
    }

    public class RobotSettings
    {
        public string Ip { get; set; }
        public string Port { get; set; }
    }

    public class PlcSettings
    {
        public string Ip { get; set; }
        public string Port { get; set; }
    }
}

And I have this in my program.cs:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace IOptions_test
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Configure services and load configuration
            // ConfigurationBuilder is used to load configuration from a settings.json file.
            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

            // Create a new ServiceCollection, which is used for Dependency Injection (DI)
            var services = new ServiceCollection();

            //This registers the Form1 type as a transient service, which means a new instance will be created every time it's requested.
            services.AddTransient<Form1>();

            // Build the ServiceProvider (DI container) from the configured services
            using var serviceProvider = services.BuildServiceProvider();

            // Retrieve the main form (Form1) from the DI container
            var mainForm = serviceProvider.GetRequiredService<Form1>();

            Application.Run(mainForm);
        }
    }
}

I try to inject the settings. The problem is that in the MainForm.cs:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace IOptions_test
{
    public partial class Form1 : Form
    {
        // Private field to hold the application settings (MyAppSettings)
        private readonly MyAppSettings _settings;

        // Constructor for Form1 that accepts IOptions<MyAppSettings> to get the settings injected by DI
        public Form1(IOptions<MyAppSettings> settings)
        {
            InitializeComponent();

            // Cast the IOptions object to ensure it's the correct type
            var options = settings as IOptions<MyAppSettings>;

            // Access the Value property to get the actual MyAppSettings object
            _settings = settings.Value;

            // Set the text of label1 to display user and IP information from the settings
            label1.Text = $"User: {_settings.User.Name}, Robot IP: {_settings.Robot.Ip}, PLC IP: {_settings.PLC.Ip}";
        }
    }
}

the _settings remain null and it throws an exception

System.InvalidOperationException: ‘Unable to resolve service for type ‘Microsoft.Extensions.Options.IOptions`1[IOptions_test.MyAppSettings]’ while attempting to activate ‘IOptions_test.Form1’

5

You actually did not register anything that would resolve to IOptions<MyAppSettings>.

In order to correct that you need to add following registration code:

services.Configure<MyAppSettings>(config);

You need to install Microsoft.Extensions.Options.ConfigurationExtensions nuget package for that.

Here’s result of the changes:

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật