In previous core version, if there is need to pass dependency while calling any function i used to pass parameter in configure method and use same value to pass as parameter while calling function.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
UserManager<IdentityUser> usermanager, RoleManager<IdentityRole rolemanager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
SeedData.Seed(userManager, roleManager);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
But in .Net 6 same flow cannot be applied due to only program.cs file. I tried to call function from program.cs file but i get : 'Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' from root provider.'
Program.cs File
using LeaveManagement;
using LeaveManagement.Data;
using LeaveManagement.Interfaces;
using LeaveManagement.Mapper;
using LeaveManagement.Repositories;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddAutoMapper(typeof(Maps));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
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();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
var userManager = app.Services.GetRequiredService<UserManager<IdentityUser>>();
var roleManager = app.Services.GetRequiredService<RoleManager<IdentityRole>>();
SeedData.Seed(userManager, roleManager);
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
I find the above solution working for some case but it is not working for me.