diff options
Diffstat (limited to 'ExamTemplate/Web/Startup.cs')
| -rw-r--r-- | ExamTemplate/Web/Startup.cs | 47 |
1 files changed, 46 insertions, 1 deletions
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<UserService>();
+ services.AddTransient<UserRepository>();
+
+ /*
+ * Database configuration
+ */
services.AddDbContext<TemplateContext>(options =>
options.UseNpgsql(this.Configuration.GetConnectionString("LocalDBConnection")));
+
+ // Needed for SignInManager and UserManager
+ services.AddIdentity<User, Role>()
+ .AddRoles<Role>()
+ .AddEntityFrameworkStores<TemplateContext>();
+
}
// 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<TemplateContext>();
+
+ dbContext.Database.Migrate();
+
+ var roleManager = (RoleManager<Role>)serviceScope.ServiceProvider.GetService(typeof(RoleManager<Role>));
+ 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();
+ }
+
}
}
}
|
