Search code examples
c#.net-5.net-6.0

.NET 5 to .NET 6 Migration Startup and Configure methodology in Minimal Hosting


I am moving my Blazor app to .NET 6 from .NET 5 and it is recommended to use the new Minimal hosting model. See Q3 in this doc. Ok. So in my .net5 app I have a typical startup and config setup but as part of that I want to call my data initialiser which checks and seeds sample data if necessary.

Yes I could change the approach, but who knows if I won't need it at another time or for something else.

My DataInitialiser uses UserManager and RoleManager, and I pass these over as part of the startup atm as follows:

            public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                 UserManager<ApplicationUser> userManager,
                 RoleManager<IdentityRole> roleManager,
                 APDbContext context,
                 APDataInitializer apDataInitializer
                 )
          {
           ...
            some stuff
           ...
            apDataInitializer.SeedData(userManager, roleManager, context);

I had done this before I had figured out properly how the DI system worked, so no issues, yes, I can inject the usermanager, rolemanager and context into the apDataInitialiser, but I am interested to know how I would do this under the new setup? ... and at the very least how to call apDataInitialiser anyway since it hasn't been injected into the app yet? ...

I have added:

// Data Initialiser
builder.Services.AddScoped<APDataInitializer>();

into the 'builder' section of the program.cs.

I just can't see how to call it from the 'app' part?

Suggestions welcome. Thanks


Solution

  • You can use app.Services to create scope and resolve needed scoped services:

    builder.Services.AddEverything....
    
    var app = builder.Build();
    using (var scope = app.Services.CreateScope())
    {
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var context = scope.ServiceProvider.GetRequiredService<APDbContext>();
        var apDataInitializer = scope.ServiceProvider.GetRequiredService<APDataInitializer>();
        apDataInitializer.SeedData(userManager, roleManager, context);
    }
    // rest of the set up