I am trying to move my ASP Identity logic to another project inside my solution.
Everything is fine except the fact that I cannot access HttpContext inside my reference library. I need to access HttpContext to seed my database using the ApplicationUserManager.
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
// Create here users and roles using userManager and roleManager
}
}
So the question is : How to access ApplicationUserManager and ApplicationRoleManager without HttpContext, or how can I access HttpContext here.
Thanks a lot
Actually, I would suggest a slightly different approach. The Identity team committed what I consider a bit of a mortal sin in bootstrapping the sample with a makeshift dependency injection container based on OWIN. Dependency injection is a great idea, but not like this. Understandably different developers prefer different DI containers, which makes creating a sample project based on a real DI container a bit of a no-go, but they should have refrained from utilizing dependency injection in the sample project and simply recommended the use of dependency injection and perhaps given guidance to implement this with various containers.
All that said, the only thing HttpContext is being used for here is to get the OWIN context, and that alone is being used to handle their half-baked dependency injection for Identity. So, if you simply inject your own UserManager with your DI container of choice, you remove the dependency on HttpContext and you're good to go.
You just need to provide configuration for two things: UserManager and IUserStore. Tell your DI container how to inject those, and then you can just add a dependency on UserManager in your library class constructor and you're ready to roll.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With