Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling class function from program.cs at runtimes in .net 6 [duplicate]

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.

like image 479
Sujan Avatar asked Oct 26 '25 10:10

Sujan


1 Answers

If you really want to get the object

var usermanager = services.BuildServiceProvider().GetService<UserManager<IdentityUser>>();

It can help (of cause, you only call it AFTER adding the services). But you can consider another way to achieve your work. Because by calling BuildServiceProvider, the framework can't guarantee the singleton scope.

like image 77
Võ Quang Hòa Avatar answered Oct 28 '25 22:10

Võ Quang Hòa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!