Need Help Migrating Activator.CreateInstances to .NET 6

Nick R 66 Reputation points
2021-11-16T21:46:56.987+00:00

Code is as follows:

public async void Configure(IApplicationBuilder app,
            IWebHostEnvironment env)
        {
            await ActivatorUtilities.CreateInstance<DatabaseInitializer>
                (app.ApplicationServices).Initialize();
        }

Need help migrating it to .NET 6. Thank you!

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,166 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Brando Zhang-MSFT 2,956 Reputation points Microsoft Vendor
    2021-11-17T02:13:55.037+00:00

    As far as I know, the ActivatorUtilities.CreateInstance is supported inside asp.net 6.

    You could directly use it inside the asp.net6 program.cs. ASP.NET6 unifies Startup.cs and Program.cs into a single Program.cs file.

    As you mentioned, the app.ApplicationServices is not existed inside asp.net 6, we should use app.Services instead.

    The code like below:

        var builder = WebApplication.CreateBuilder(args);
    
        // Add services to the container.
        builder.Services.AddControllersWithViews();
    
        var app = builder.Build();
    
    
    
        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/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();
        }
    
    await ActivatorUtilities.CreateInstance<DatabaseInitializer>
                 (app.Services).Initialize();
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
    
        //app.UseAuthentication();    
        app.UseRouting();
    
        //app.UseAuthorization();
    
        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    
        app.Run();