Добавить начальные данные

***
- Добавил сервис по добавлению начальных данных.
- Прокинул инициализацию данных в Program. Теперь при старте программы, если в БД нет ролей и/или админа, то они добавятся.
***
parent 68ade2ba
...@@ -3,17 +3,35 @@ using System.Collections.Generic; ...@@ -3,17 +3,35 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using PhoneStore.Models;
using PhoneStore.Services;
namespace PhoneStore namespace PhoneStore
{ {
public class Program public class Program
{ {
public static void Main(string[] args) public static async Task Main(string[] args)
{ {
CreateHostBuilder(args).Build().Run(); var host = CreateHostBuilder(args).Build();
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var userManager = services.GetRequiredService<UserManager<User>>();
RoleManager<Role> rolesManager = services.GetRequiredService<RoleManager<Role>>();
await AdminInitializer.SeedAdminUser(rolesManager, userManager);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Не удалось добавить начальные данные в БД");
}
await host.RunAsync();
} }
public static IHostBuilder CreateHostBuilder(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args) =>
......
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using PhoneStore.Models;
namespace PhoneStore.Services
{
public class AdminInitializer
{
public static async Task SeedAdminUser(
RoleManager<Role> roleManager,
UserManager<User> userManager)
{
string adminEmail = "admin@admin.com";
string adminPassword = "Admin1234@";
var roles = new [] { "admin", "user" };
foreach (var role in roles)
{
if (await roleManager.FindByNameAsync(role) is null)
await roleManager.CreateAsync(new Role(role));
}
if (await userManager.FindByNameAsync(adminEmail) == null)
{
User admin = new User { Email = adminEmail, UserName = adminEmail };
IdentityResult result = await userManager.CreateAsync(admin, adminPassword);
if (result.Succeeded)
await userManager.AddToRoleAsync(admin, "admin");
}
}
}
}
\ No newline at end of file
...@@ -22,11 +22,12 @@ namespace PhoneStore ...@@ -22,11 +22,12 @@ namespace PhoneStore
public IConfiguration Configuration { get; } public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
string connection = Configuration.GetConnectionString("DefaultConnection"); string connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MobileContext>(options => options.UseNpgsql(connection)); services.AddDbContext<MobileContext>(options => options.UseNpgsql(connection))
.AddIdentity<User, Role>()
.AddEntityFrameworkStores<MobileContext>();
services.AddControllersWithViews(); services.AddControllersWithViews();
services.AddApplicationServices(Configuration); services.AddApplicationServices(Configuration);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment