From 57cc5682a0efe2b790015f77fe9d2e2a0bb6ed87 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 6 May 2021 21:52:47 +0300 Subject: Added automapper; Implemented user register; Improved some database configurations --- ExamTemplate/Web/Startup.cs | 47 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) (limited to 'ExamTemplate/Web/Startup.cs') diff --git a/ExamTemplate/Web/Startup.cs b/ExamTemplate/Web/Startup.cs index e66e40a..9c43601 100644 --- a/ExamTemplate/Web/Startup.cs +++ b/ExamTemplate/Web/Startup.cs @@ -1,6 +1,12 @@ +using System; +using System.Linq; using ExamTemplate.Data; +using ExamTemplate.Data.Models; +using ExamTemplate.Data.Repositories; +using ExamTemplate.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -21,10 +27,26 @@ namespace Web public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); + services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); - // Database configuration + /* + * Dependency Injection configuration + */ + + services.AddTransient(); + services.AddTransient(); + + /* + * Database configuration + */ services.AddDbContext(options => options.UseNpgsql(this.Configuration.GetConnectionString("LocalDBConnection"))); + + // Needed for SignInManager and UserManager + services.AddIdentity() + .AddRoles() + .AddEntityFrameworkStores(); + } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -54,6 +76,29 @@ namespace Web name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); + + /* + * Make sure that the database is migrated + * and that the User and Admin role exist in database + */ + + using var serviceScope = app.ApplicationServices.CreateScope(); + using var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + + dbContext.Database.Migrate(); + + var roleManager = (RoleManager)serviceScope.ServiceProvider.GetService(typeof(RoleManager)); + if (!dbContext.Roles.Any(x => x.Name == Role.UserRole)) + { + Role userRole = new() { Name = Role.UserRole }; + roleManager.CreateAsync(userRole).Wait(); + } + if (!dbContext.Roles.Any(x => x.Name == Role.AdminRole)) + { + Role adminRole = new() { Name = Role.AdminRole }; + roleManager.CreateAsync(adminRole).Wait(); + } + } } } -- cgit v1.2.3