在 ASP.Net 5 中配置一个组件

Configure a component in ASP.Net 5

在 ASP.Net 5 中有不同的配置组件的方法:

ConfigureXXX()方法负责配置组件或子组件:

https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNet.Authorization/ServiceCollectionExtensions.cs#L12

public static IServiceCollection ConfigureAuthorization(
    [NotNull] this IServiceCollection services, 
    [NotNull] Action<AuthorizationOptions> configure)
{
    return services.Configure(configure);
}

https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.Core/DependencyInjection/MvcCoreServiceCollectionExtensions.cs#L50

public static void ConfigureMvc(
    [NotNull] this IServiceCollection services,
    [NotNull] Action<MvcOptions> setupAction)
{
    services.Configure(setupAction);
}

但有时 ConfigureXXX 有点复杂: https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNet.Authentication.Cookies/CookieServiceCollectionExtensions.cs#L31

public static IServiceCollection ConfigureCookieAuthentication(
    [NotNull] this IServiceCollection services, 
    [NotNull] IConfiguration config, 
    string optionsName)
{
    return services.Configure<CookieAuthenticationOptions>(config, optionsName);
}

为什么一些现有组件比其他组件 "configurables" 多?

作为组件编写者,我该练些什么?

另一个相关问题: AddXXX & UseXXX 有时允许配置组件: https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.Core/DependencyInjection/MvcCoreServiceCollectionExtensions.cs#L32

public static IMvcBuilder AddMvcCore(
    [NotNull] this IServiceCollection services,
    [NotNull] Action<MvcOptions> setupAction)
{
    ConfigureDefaultServices(services);
    AddMvcCoreServices(services);
    services.Configure(setupAction);
    return new MvcBuilder() { Services = services, };
}

https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNet.Authentication.OAuth/OAuthAuthenticationExtensions.cs#L22

public static IApplicationBuilder UseOAuthAuthentication(
    [NotNull] this IApplicationBuilder app, 
    [NotNull] string authenticationScheme, 
    Action<OAuthAuthenticationOptions> configureOptions = null)
{
    return app.UseMiddleware<OAuthAuthenticationMiddleware<OAuthAuthenticationOptions>>(
    // [...]
}

基本上,使用三种不同的方法配置选项之间的语义区别是什么?特别是当它在同一组件上可用时。

因此,对于使用 IOptions 服务的选项和任何组件,我们的想法是让在堆栈中的任何位置配置选项(添加、使用、配置)变得容易,它们都是有效的,但顺序很重要。

我们一直使用的一般模式通常是 Action<YourOptions> 看起来有用的地方。