New to MVC.
I seem to be stuck in a bit of a Catch-21 (not quite as severe as a Catch-22).
To keep unnecessary database traffic down, I'd like to call my method to populate the initial Identity data (create admin user, admin role, etc.) only when the database is first created (e.g. during CreateDatabaseIfNotExists(Of ApplicationDbContext)
).
The trouble stems from the fact that my Startup config must set the DbContext
first, before ApplicationUserManager
and ApplicationSignInManager
are set:
Builder.CreatePerOwinContext(AddressOf ApplicationDbContext.Create)
Builder.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create)
Builder.CreatePerOwinContext(Of ApplicationSignInManager)(AddressOf ApplicationSignInManager.Create)
The ApplicationUserManager.Create()
method calls ApplicationDbContext
, so the calls have to be in that order.
Here's the relevant bit of my Identity initialization code:
Public Shared Sub InitializeIdentity()
Dim oUserManager As ApplicationUserManager
Dim oRoleManager As ApplicationRoleManager
oUserManager = HttpContext.Current.GetOwinContext.GetUserManager(Of ApplicationUserManager)
oRoleManager = HttpContext.Current.GetOwinContext.Get(Of ApplicationRoleManager)
...
End Sub
See the problem? ApplicationUserManager
relies on ApplicationDbContext
and ApplicationDbContext
relies on ApplicationUserManager
(the latter only when I try to run InitializeIdentity()
from the overridden Migrations.Configuration.Seed()
method).
Sure, I could put the InitializeIdentity()
call elsewhere in my startup, but then it'd run on every single page load when it only needs to run once when the database is first created. That's a huge amount of completely unnecessary hits to the database.
Is there a way to escape this logic loop? How can I tell the framework to run the Identity initialization after ApplicationUserManager
is set—only once, upon database creation—when the context has to be set first?