mi puoi consigliare come migliorare la gestione del mio program.cs per delle web api in c# "using EuroItalia.Middleware.Configuration;
using EuroItalia.Middleware.Entity;
using EuroItalia.Middleware.Logger;
using EuroItalia.Middleware.Repository;
using log4net.Config;
using log4net;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using MongoDB.Driver;
using System.Reflection;
using System.Text;
using log4net.Core;

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;

string assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

// leggo il file di configurazione, nella sottocartella Impostazioni dell'EXE
string configurationPath = Path.Combine(Path.GetDirectoryName(assemblyLocation), "Impostazioni");
if (!Directory.Exists(configurationPath)) Directory.CreateDirectory(configurationPath);
MiddlewareConfiguration config = MiddlewareConfiguration.CaricaConfigurazione(assemblyName, "Middleware", configurationPath, typeof(MiddlewareConfiguration)) as MiddlewareConfiguration;
// se non c'è il file di configurazione creo la classe base
if (config == null) config = new MiddlewareConfiguration(assemblyName, "Middleware", configurationPath);

bool temp = false;
if (temp) config.SalvaConfigurazione();
// Add services to the container.

builder.Services.AddSingleton<IMongoClient>(sp =>
{
    return new MongoClient(config.ConnectionString);
});

// Registra un servizio di accesso al database (ad es.)
builder.Services.AddScoped<IMongoDatabase>(sp =>
{
    var client = sp.GetRequiredService<IMongoClient>();
    return client.GetDatabase(config.DatabaseName);
});

builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<ILogRepository, LogRepository>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IMiddlewareLogger, MiddlewareLogger>();


builder.Services.AddControllers();

if (config.AuthenticationType == AuthenticationType.Basic)
{
    builder.Services.AddAuthentication("BasicAuthentication")
        .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
}
else if (config.AuthenticationType == AuthenticationType.JWT)
{
    var jwtSettings = configuration.GetSection("Jwt");
    var key = Encoding.UTF8.GetBytes(jwtSettings.GetValue<string>("Key"));

    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtSettings.GetValue<string>("Issuer"),
                ValidateAudience = true,
                ValidAudience = jwtSettings.GetValue<string>("Audience"),
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateLifetime = true
            };
        });
}
else
{
    throw new Exception("Authentication scheme not configured correctly.");
}

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });


    if (config.AuthenticationType == AuthenticationType.Basic)
    {
        // Aggiungi schema di sicurezza basic
        c.AddSecurityDefinition("basic", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
        {
            Name = "Authorization",
            Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
            Scheme = "basic",
            In = Microsoft.OpenApi.Models.ParameterLocation.Header,
            Description = "Autenticazione Basic usando username e password"
        });

        // Specifica che tutte le chiamate richiedono autenticazione basic
        c.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new Microsoft.OpenApi.Models.OpenApiSecurityScheme
            {
                Reference = new Microsoft.OpenApi.Models.OpenApiReference
                {
                    Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                    Id = "basic"
                }
            },
            new string[]{ }
        }
    });
    }
    else if (config.AuthenticationType == AuthenticationType.JWT)
    {
        c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            In = ParameterLocation.Header,
            Description = "Inserisci il tuo Bearer token",
            Scheme = "Bearer",
            Name = "Authorization",
            Type = SecuritySchemeType.Http,
        });

        c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] { }
        }
    });
    }
    else
    {
        throw new Exception("Authentication scheme not configured correctly.");
    }
});

var app = builder.Build();


using (var scope = app.Services.CreateScope())
{
    var userRepository = scope.ServiceProvider.GetRequiredService<IUserRepository>();


    if (userRepository.IsUsersCollectionEmpty())
    {
        var user = new User
        {
            Name = "admin",
            Password = "123"
        };
        userRepository.CreateUser(user);
    }
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();"?