Background and Motivation
In .NET 7, we introduced an AddAuthorizationBuilder extension method on IServiceCollection that would register authorization-related services and provide an AuthorizationBuilder for constructing policies. This is an abbreviated syntax that allows reduces nesting in the original pattern of calling AddAuthorization and providing a policy construct as a callback.
Proposed Analyzer
Analyzer Behavior and Message
When the user provides code where AddAuthorizationBuilder would provide a more abbreviated style, recommend a codefix with the following message:
Use AddAuthorizationBuilder to register authorization services and construct policies.
Category
Severity Level
Usage Scenarios
Before
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AtLeast21", policy =>
policy.Requirements.Add(new MinimumAgeRequirement(21)));
});
var app = builder.Build();
app.UseAuthorization();
app.Run();
After
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AtLeast21", policy =>
{
policy.Requirements.Add(new MinimumAgeRequirement(21)));
});
var app = builder.Build();
app.UseAuthorization();
app.Run();
Risks
Marking this as an info-only analyzer strikes a good balance between informing the user of this feature without being too presumptuous (via a warning). A refactoring would not have been good at educating the user about the functionality.
Background and Motivation
In .NET 7, we introduced an
AddAuthorizationBuilderextension method onIServiceCollectionthat would register authorization-related services and provide anAuthorizationBuilderfor constructing policies. This is an abbreviated syntax that allows reduces nesting in the original pattern of callingAddAuthorizationand providing a policy construct as a callback.Proposed Analyzer
Analyzer Behavior and Message
When the user provides code where
AddAuthorizationBuilderwould provide a more abbreviated style, recommend a codefix with the following message:Category
Severity Level
Usage Scenarios
Before
After
Risks
Marking this as an info-only analyzer strikes a good balance between informing the user of this feature without being too presumptuous (via a warning). A refactoring would not have been good at educating the user about the functionality.