Home > Net >  How to Add Scoped Model from mvc 5 to mvc 6?
How to Add Scoped Model from mvc 5 to mvc 6?

Time:10-28

Hy there,

I am stuck at converting Scoped Service from MVC 5 to 6. I wanted to seed with Roles a entity database, I created a Model but in the course i look it have mvc5.

I tried to adapt to mvc 6, didn't successed.

My UserRoleInitializer Model:

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
namespace eVote.Models
{
    public static class UserRoleInitializer
    {
        public static async Task InitializeAsync(IServiceProvider serviceProvider)
        {
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<DefaultUser>>();

            string[] roleNames = { "Admin", "User" };

            IdentityResult roleResult;

            foreach (var role in roleNames)
            {
                var roleExists = await roleManager.RoleExistsAsync(role);

                if (!roleExists)
                {
                    roleResult = await roleManager.CreateAsync(new IdentityRole(role));
                }
            }

            var email = "[email protected]";
            var password = "Qwerty123!";

            if (userManager.FindByEmailAsync(email).Result == null)
            {
                DefaultUser user = new()
                {
                    Email = email,
                    UserName = email,
                    FirstName = "Admin",
                    LastName = "Adminsson",
                    Address = "Adstreet 3",
                    City = "Big City",
                    ZipCode = "12345"
                };

                IdentityResult result = userManager.CreateAsync(user, password).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Admin").Wait();
                }
            }

        }
    }
}

MVC 5 solution enter image description here

How can I implement these lines in MVC 6 in Program.cs?

CodePudding user response:

If you wanna configure it in .Net6, You can use this code:

Program.cs

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var service = scope.ServiceProvider;
    try
    {
        await UserRoleInitializer.InitializeAsync(service);
    }
    catch (Exception ex)
    {
        //..........
    }
}

//other middlewares
  • Related