Setting up a component in ASP.Net 5
There are different ways to configure a component in ASP.Net 5:
- the AddXXX method used to add services,
- the ConfigureXXX method used to configure parameters,
- UseXXX method, use to register middleware in the pipeline.
The ConfigureXXX () method is responsible for configuring a component or subcomponent:
public static IServiceCollection ConfigureAuthorization(
[NotNull] this IServiceCollection services,
[NotNull] Action<AuthorizationOptions> configure)
{
return services.Configure(configure);
}
public static void ConfigureMvc(
[NotNull] this IServiceCollection services,
[NotNull] Action<MvcOptions> setupAction)
{
services.Configure(setupAction);
}
But sometimes ConfigureXXX is a little more complicated: 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);
}
Why are some existing components more “customizable” than others?
As a component writer, what should I practice?
Another related question: Sometimes AddXXX and UseXXX let you customize a component: 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, };
}
public static IApplicationBuilder UseOAuthAuthentication(
[NotNull] this IApplicationBuilder app,
[NotNull] string authenticationScheme,
Action<OAuthAuthenticationOptions> configureOptions = null)
{
return app.UseMiddleware<OAuthAuthenticationMiddleware<OAuthAuthenticationOptions>>(
// [...]
}
Basically, what's the difference between setting parameters using three different methods? Especially when it's available on a single component.
source to share
So with parameters and any component using the IOptions service, the idea was to make it easier to configure the parameters at any point in the stack (Add, Use, Configure), they are all valid, but the order matters.
The general pattern we have used usually takes Action<YourOptions>
wherever it might seem useful.
source to share