Home > Net >  Options pattern (IOptions) C# .Net 6.0 Windows Form
Options pattern (IOptions) C# .Net 6.0 Windows Form

Time:06-06

I am writing a simple test application on Windows Form. I need to pass the configuration via IOptions. There are two values in the configuration: AccessKey and SecretKey. I will need to get these values on the main form. Here is my code:

//appsettings.json:

{
  "ConnectionString:AccessKey": "FDJKSFDJF",
  "ConnectionString:SecretKey": "KSDHFKDJF"
}


public class ConnectionString
{
    public string? AccessKey { get; set; }
    public string? SecretKey { get; set; }
}


 public static class Startup
 {
        public static IServiceProvider? ServiceProvider;
        private static readonly IConfiguration Configuration;
        public static ConnectionString connectionString { get; set; }

        static Startup()
        {
           var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
           var AppConfiguration = builder.Build();
        }
 }


//the class in which I need to get the values:

public partial class MainForm : Form
    {
       public ConnectionString connectionString { get; }

        public MainForm()
        {
            InitializeComponent();

            MessageBox.Show(connectionString.AccessKey);
           
        }

        public MainForm(IOptions<ConnectionString> options)
        {
            connectionString = options.Value;
        }
}

with this code, I get the error System.NullReferenceException: "Object reference not set to an instance of an object.". I understand that my file .json has nothing to do with my class right now. help meeee.

CodePudding user response:

Here is an example of how to use DI together with windows forms application.

internal static class Program
{
    public static IHost? CurrentHost { get; private set; }
    
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        // To customize application configuration such as set high DPI settings or default font,
        // see https://aka.ms/applicationconfiguration.
        ApplicationConfiguration.Initialize();       

        CurrentHost = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    //Registers a config instance which TOptions will bind against.
                    services.Configure<ConnectionString>(context.Configuration.GetSection("ConnectionStrings"));
                    services.AddScoped<MainForm>();                    
                })
                //sets up the configuration
                .ConfigureAppConfiguration(context => BuildConfig(context))
                .Build();

        using IServiceScope serviceScope = CurrentHost.Services.CreateScope();
        IServiceProvider provider = serviceScope.ServiceProvider;
        var mainForm = provider.GetRequiredService<MainForm>();
        Application.Run(mainForm);
    }

    static void BuildConfig(IConfigurationBuilder builder)
    {
        builder.SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .AddEnvironmentVariables();
    }
}

And then you can inject IOptions<ConnectionString> from the constructor of the MainForm

public partial class MainForm : Form
{
    public MainForm(IOptions<ConnectionString> options)
    {
        var connString = options.Value;
        InitializeComponent();        
    }
}
  •  Tags:  
  • c#
  • Related