SA1200 in the new .NET 6 Program.cs

982 Views Asked by At

.NET 6 introduces a new bootstrap syntax that replaces the old Program.cs/Startup.cs mishmosh. The standard template looks like this:

using ThetaRex.Common;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

This is all great and good, until you start adding your own code or some other package. Then we start getting SA1200 errors telling us the 'using' statements should be inside a namespace.

warning SA1200: Using directive should appear within a namespace declaration

What is the recommended way of handling the new .NET 6 syntax for program.cs? As a rule, I try to avoid any and all customization of the rules, opting instead to change my code to work with StyleCop out-of-the-box if possible. Is this new bootstrap compatible with StyleCop?

1

There are 1 best solutions below

9
On

You can also use the new global usings if you will be using the namespaces throughout your code.

Simply create a file called Imports.cs (and/or _Imports.razor for Blazor) and put your usings there.

Imports.cs:

global using Microsoft.AspNetCore.Components.Web;
global using System;
global using System.Collections.Generic;
global using System.Linq;

_Imports.razor:

@using System.Net.Http
@using System.Net.Http.Json
@using System.Text.Json