Hi,
I am trying to use DI with a console app. The Identity migrations work fine. However, serviceProvider.GetService for my own DbContext does ever call OnModelCreating, to add the DbSets to the DbContext. When I try to access one of the DbSets defined in ResolveROIContext, the code branch simple returns. If I trace the code, it never hits OnModelCreating.
public class Startup
{
public static IConfigurationRoot Configuration { get; set; }
public static void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<ResolveROIContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
}
public static void Main(string[] args)
{
var services = new ServiceCollection();
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
ConfigureServices(services);
var provider = services.BuildServiceProvider();
Task task = Task.Run(async () =>
{
await InitializeData.Initialize(provider);
});
}
}
public class InitializeData
{
public static async Task<bool> Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
context.Database.Migrate();
await SeedUsers(serviceProvider);
return true;
}
public static async Task<bool> SeedUsers(IServiceProvider serviceProvider)
{
// Get Identity DbContext from Dependency Injection.
var xIdentity = serviceProvider.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
// Get Identity UserManager from Dependency Injection.
var userManager = serviceProvider.GetService(typeof(UserManager<ApplicationUser>)) as UserManager<ApplicationUser>;
// Get Identity RolerManager from Dependency Injection.
var roleManager = serviceProvider.GetService(typeof(RoleManager<ApplicationRole>)) as RoleManager<ApplicationRole>;
var xResolve = serviceProvider.GetService(typeof(ResolveROIContext)) as ResolveROIContext;
Thanks,
David