如何在UWP程序中将ConfigurationRoot添加到依赖注入?

问题描述 投票:0回答:1

在我的UWP应用程序中,我可以使用Microsoft.Extensions.Configuration包来读取JSON格式的appSettings文件。

    IConfiguration configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", true, true)
        .AddJsonFile($"appsettings.{App.UWPENVIRONMENT}.json", true, true)
        .Build();
    string clientId = configuration["security:clientId"];
    string authority = configuration["security:authority"];

我现在似乎无法做的是使用System.Composition依赖注入使配置可用于我的UWP应用程序的其余部分。由于构建配置对象的方式(使用Build方法),我无法弄清楚如何在某种构造函数中嵌入此配置。

想到的一个选项是我可以将接口与对象关联,如下所示:

        conventions.ForObject(configuration)
            .Shared()
            .Export(ecb => ecb.AsContractType<IConfiguration>());

但DI包似乎不支持这种思维方式。我该如何解决这个问题:

  1. 找到一种构建类型的方法。
  2. 将接口与具体实例相关联。
  3. 其他
.net dependency-injection uwp configuration
1个回答
0
投票

以下是创建类型化ConfigurationRoot的代码:

    /// <summary>
    /// The configuration for this application.
    /// </summary>
    public class ApplicationConfiguration : ConfigurationRoot
    {
        /// <summary>
        /// The client id of the service application to which we want to connect.
        /// </summary>
#if PRODUCTION
        private const string UWPENVIRONMENT = "Production";
#elif STAGING
        private const string UWPENVIRONMENT = "Staging";
#else
        private const string UWPENVIRONMENT = "Development";
#endif

        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationConfiguration"/> class.
        /// </summary>
        public ApplicationConfiguration()
            : base(ApplicationConfiguration.GetProviders())
        {
        }

        /// <summary>
        /// Gets the configuration providers.
        /// </summary>
        /// <returns>A list of the configuration providers.</returns>
        private static List<IConfigurationProvider> GetProviders()
        {
            // Build a configuration that reads from the appsettings.json files and extract the providers.
            IConfigurationRoot configurationRoot = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{ApplicationConfiguration.UWPENVIRONMENT}.json", true, true)
                .Build();
            return configurationRoot.Providers.ToList();
        }
    }

并将其添加到DI:

    conventions.ForType<ApplicationConfiguration>().Shared().Export(ecb => ecb.AsContractType<IConfiguration>());

您的客户端现在将使用与.NET Core Web服务大致相同的配置文件。

© www.soinside.com 2019 - 2024. All rights reserved.