验证MVC Core中的配置

时间:2017-01-09 03:15:33

标签: asp.net-mvc asp.net-core asp.net-core-mvc

我在appsettings.json中有一个部分,其中包含库及其依赖项的列表,以及如何在不同的执行环境中配置它们。我希望能够验证库集合包含所有依赖项。< / p>

这很容易做一点递归。但我无法弄清楚如何覆盖配置绑定过程,以便我可以进行验证。

我想出的唯一方法是基于appconfig.json创建库的原始集合,然后创建一个验证集合并使其可用的服务。类似的东西:

public class RawLibraries : List<Library>
{
}

public class LibraryResolver
{
    public LibraryResolver( IOptions<RawLibraries> rawLibs, ILogger logger )
    {
        // validate rawLibs and log errors
    }
    // ...implementation
}

services.Configure<RawLibraries>(Configuration.GetSection("Libraries"));

services.AddSingleton<LibraryResolver, LibraryResolver>();

但这似乎令人费解。关于更好方法的想法?

1 个答案:

答案 0 :(得分:1)

为什么不跟随作者并使用额外的验证编写自己的扩展方法?

看看这里。这是services.Configure<>方法的源代码:

namespace Microsoft.Extensions.DependencyInjection
{
  /// <summary>
  /// Extension methods for adding options services to the DI container.
  /// </summary>
  public static class OptionsServiceCollectionExtensions
  {
    ...

    /// <summary>
    /// Registers an action used to configure a particular type of options.
    /// </summary>
    /// <typeparam name="TOptions">The options type to be configured.</typeparam>
    /// <param name="services">The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> to add the services to.</param>
    /// <param name="configureOptions">The action used to configure the options.</param>
    /// <returns>The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> so that additional calls can be chained.</returns>
    public static IServiceCollection Configure<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class
    {
      if (services == null)
        throw new ArgumentNullException("services");
      if (configureOptions == null)
        throw new ArgumentNullException("configureOptions");
      services.AddSingleton<IConfigureOptions<TOptions>>((IConfigureOptions<TOptions>) new ConfigureOptions<TOptions>(configureOptions));
      return services;
    }
  }
}

如您所见,Configure<TOptions>方法是一种扩展方法。只需编写自己的简单ConfigureAndValidate<TOptions>()扩展方法,该方法将在services.AddSingleton...行之前进行适当的验证。