2017-01-09 38 views
0

我在appsettings.json中有一個部分,其中包含一系列庫及其依賴關係,以及如何在不同的執行環境中配置它們。我想驗證庫集合包含所有的依賴關係。在MVC Core中驗證配置

這很容易做到一點點遞歸。但我無法弄清楚如何覆蓋配置綁定過程,以便我可以進行驗證。

我想出的唯一方法是基於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

爲什麼不按照作者的方式編寫自己的擴展方法和附加驗證?

看看這裏。這是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...行之前做適當的驗證。

+0

我的不好!我仍然習慣於能夠把所有這些東西都放在一起。 Thanx,David! –