Files

40 lines
1.7 KiB
C#

using FJPSite.Attributes;
using FJPSite.Data;
using FJPSite.Extensions;
using FJPSite.Interfaces;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Reflection;
namespace FJPSite.Factories;
public static class DbSeederFactory
{
public static void SeedDatabase(ApplicationDbContext context)
{
//TODO: Code works, just not sure if want to auto load/inject due to some needing to be done in a specific order.
var serviceDescriptors = typeof(Program).Assembly//.GetTypes().Where(type => type is {IsAbstract: false, IsInterface: false } && type.IsAssignableFrom(typeof(IEntitySeederFactory))).OrderBy(o => o.GetCustomAttribute<SeedOrderAttribute>().Order)
.DefinedTypes
.Where(type => type is { IsAbstract: false, IsInterface: false } &&
type.IsAssignableTo(typeof(IEntitySeederFactory))).OrderBy(o => o.GetCustomAttribute<SeedMigrationAttribute>().Migration)
.ToArray();
//
foreach (var serviceDescriptor in serviceDescriptors)
{
if (context.MigrationApplied(serviceDescriptor.GetCustomAttribute<SeedMigrationAttribute>().Migration))
{
IEntitySeederFactory entitySeederFactory = Activator.CreateInstance(serviceDescriptor) as IEntitySeederFactory;
entitySeederFactory.Seed(context);
}
}
/*Reflection
IdentitySeederFactory identitySeeder = new IdentitySeederFactory();
identitySeeder.Seed(context);
PermissionSeederFactory permissionSeeder = new PermissionSeederFactory();
permissionSeeder.Seed(context);*/
}
}