Provide information diagnostic when public partial class Program { } declaration is found in code (original) (raw)

Background and Motivation

With the introduction of top-level statements in .NET 6, there is not longer an explicit Program class defined in user's ASP.NET Core applications. Instead, we rely on the Program class generated by the compiler, which has a default visibility of internal.

This introduces an annoying hurdle for users who want to write integration tests on top of our WebApplicationFactory which requires a public entrypoint as a generic type argument.

To work around this, we document that users can either:

The first approach runs the risk of the user having to expose truly internal types to their test code. The second approach is hard to discover.

To resolve this issue, we introduced a new source generator to the shared framework that will emit the public partial class Program {} declaration to applications that:

This source generator was implemented in #58199. Based on the code generation that we introduced here, users can get rid of the explicit public partial class Program { } declarations in their source code and rely on the new default behavior. We propose introducing an analyzer to find these explicit declarations and a code fixer to remove them.

Proposed Analyzer

Analyzer Behavior and Message

Title

Explicit class declaration not required

Message

Using public partial class Program { } to make generated Program class public is no longer required. See https://aka.ms/aspnetcore-warnings/ASP0027 for more details.

Category

Severity Level

Usage Scenarios

using Microsoft.AspNetCore.Builder;

var app = WebApplication.Create();

app.MapGet("/", () => "Hello, World!");

app.Run();

public partial class Program {} // Emit info diagnostic here