【问题标题】:How to read appsettings.json in WPF Prism application如何在 WPF Prism 应用程序中读取 appsettings.json
【发布时间】:2022-06-10 18:47:54
【问题描述】:

在纯 WPF 应用程序中,我可以使用 HostBuilder,如下所示。但我怎么能在 Prism 应用程序中做同样的事情呢?我读到的内容,在 Prism 中无法使用 HostBuild(根据 Brian Lagunas 的说法,这没有意义 - 找不到链接)。

有人能指出正确的方向或分享代码吗?

public App()
        {
            _host = new HostBuilder()
                .ConfigureAppConfiguration((context, configurationBuilder) =>
                {
                    configurationBuilder.SetBasePath(context.HostingEnvironment.ContentRootPath);
                    configurationBuilder.AddJsonFile("appsettings.json", optional: false);
                })
                .ConfigureServices((context, services) =>
                {
                    services.Configure<AppSettings>(context.Configuration);

                    services.AddDbContext<VisitorDbContext>(options =>
                        options.UseSqlServer(context.Configuration.GetConnectionString("DefaultConnection")));

                    services.AddScoped<ISampleService, SampleService>();
                    services.AddScoped<IImportService, ImportService>();
                    services.AddSingleton<MainWindow>();
                })
                .ConfigureLogging(logging =>
                {
                    //logging.AddConsole();
                })
                .Build();
        }

【问题讨论】:

    标签: wpf prism


    【解决方案1】:

    如果您使用 .NET 主机来解析应用设置,您可以覆盖 Prism App.xaml.cs 类的 RegisterTypes 方法以将 IOptions&lt;T&gt; 注册到应用:

    public partial class App : PrismApplication
    {
        private readonly IHost _host;
    
        public App()
        {
            _host = ...;
        }
    
        ...
    
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterInstance(
               _host.Services.GetService<IOptions<AppSettings>>());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多