ASP Identity - Access HttpContext in the Help Library

I am trying to move ASP Identity logic to another project inside my solution.

Everything is fine except that I cannot access the HttpContext inside my help library. I need to access the HttpContext in order to seed my database using 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

+1
source share
2 answers

Actually, I would suggest a slightly different approach. The Identity team did what I consider a bit of a deadly sin when loading a sample using an OWIN-based impromptu dependency injection container. Injection injection is a great idea, but not like that. It is clear that different developers prefer different DI containers, which makes creating a standard project based on a real DI container a little bad, but they should refrain from using dependency injection in the sample project and just recommend using dependency injection and maybe instructions are given for implementing this with various containers.

All that was said, the only thing used by HttpContext is to get the OWIN context, and this in itself is used to handle their fading dependency injection for Identity. So, if you just enter your own UserManager with the selected DI container, you will remove the HttpContext dependency and you will be fine.

You just need to provide a configuration for two things: UserManager and IUserStore . Tell your DI container how to enter it, and then you can just add the dependency on UserManager to your library class constructor, and you're ready to go.

+7
source

In fact, I was able to access it by doing:

 public static void InitializeIdentityForEF(IdentityDbContext db) { var userManager = new ApplicationUserManager(new ApplicationUserStore(db)); var roleManager = new ApplicationRoleManager(new ApplicationRoleStore(db)); } 
+3
source

All Articles