How do I migrate this into my .NET 6 Program.cs file without using the startup class? The code is from .NET Core 2.1, also in Program.cs
Asked Answered
T

1

-2

I want to add this to my program.cs without having to use a startup class.

I've read the Microsoft docs but can't seem to get it to work.

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();
    InitializeDatabase(host);
    host.Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

public static void InitializeDatabase(IWebHost host)
{
    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;

        try
        {
            SeedData.InitializeAsync(services).Wait();
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred seeding the database.");
        }
    }
}
Thrill answered 5/8, 2022 at 18:58 Comment(0)
M
0

Firstly, the documentation doesn't suggest/guide on upgrade from 2.1 to .net6. you can try refer to follow the steps based on the side menu below 'migration' menu. https://learn.microsoft.com/en-us/aspnet/core/migration/31-to-60?view=aspnetcore-6.0&tabs=visual-studio

However, there are few breaking changes in between, I am not sure if you want to go for a version by version upgrade. Anyhow, for the initialize classes, you can declare without access modifier, in the program.cs for .net6 and if you want to drop startup.cs , you actually do not need most of classic setup code the old code in startup.cs too.

Eg in program.cs:
var builder = WebApplication.CreateBuilder(args);
....
....
MyInitializeMethod(app);
app.MapRazorPages();
app.Run();

static void MyInitializeMethod(IApplicationBuilder app)
{
.....
....
}

But if you like to keep the startup class, maybe you shall consider for .net5 because we still have startup.cs in .net 5, and good news is .net6 will still understand it.

Macomber answered 1/9, 2022 at 3:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.