简体   繁体   English

选项模式 (IOptions) C# .Net 6.0 Windows 窗体

[英]Options pattern (IOptions) C# .Net 6.0 Windows Form

I am writing a simple test application on Windows Form.我正在 Windows 窗体上编写一个简单的测试应用程序。 I need to pass the configuration via IOptions.我需要通过 IOptions 传递配置。 There are two values in the configuration: AccessKey and SecretKey.配置中有两个值:AccessKey 和 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.".使用此代码,我收到错误 System.NullReferenceException:“对象引用未设置为对象的实例。”。 I understand that my file .json has nothing to do with my class right now.我知道我的文件 .json 现在与我的班级无关。 help meeee.帮助meeee。

Here is an example of how to use DI together with windows forms application.这是一个如何将 DI 与 windows 窗体应用程序一起使用的示例。

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然后你可以从MainForm的构造函数中注入IOptions<ConnectionString>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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