1

I am looking for the correct way to get access to the UserManager<MyUser> object outside of a controller using the most recent incarnation of ASP.NET MVC 5 and Entity Framework 7.

I want to seed my database with users in my seed class, but I have been unable to find a way to access the UserManager object to do so.

The Visual Studio 2015 Update 1 default ASP.NET template reveals the statement app.UseIdentity() in the Startup.Configure method while the Account controller accepts the UserManager<MyUser> in its constructor.

How do I access the UserManager in other classes so that I can create seed users?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ChiliYago
  • 11,341
  • 23
  • 79
  • 126
  • Have you seen this post: http://stackoverflow.com/questions/23574591/seed-database-for-identity-2 – David Tansey Dec 29 '15 at 16:32
  • That helps a little but it is referring to Owin Contexts which I don't think are applicable in the most current way to do this.. – ChiliYago Dec 29 '15 at 16:37
  • The version of MVC that you are using is MVC6 isn't it? I.E. The latest version. You might have more help tagging it as MVC6 and Editing your question slightly? – GavKilbride Dec 29 '15 at 23:41
  • From the little I know about ASP.NET5 and MVC6 the UserManager is registered with the built in dependency injection. I believe you just need to add it to the constructor of the consuming class and you should be able to use it. Assuming APS.NET is responsible for the construction of that class. The other option is the Service Locator pattern, which although a bit of an anti-pattern it can get you out of a jam. This might help? http://www.emadashi.com/2015/06/dependency-injection-in-asp-net-5-one-step-deeper/ – GavKilbride Dec 29 '15 at 23:47
  • 1
    @GavKilbride you seem to be correct. It was adding UserManager userManager to the seed class's constructor that allowed me to easily add users. You should post your suggestion and an answer to get the credit for the help. Thanks – ChiliYago Dec 30 '15 at 13:19
  • Glad it pointed you in the right direction. I reworded the answer to sound a little more definitive and less like a guess ;-) – GavKilbride Dec 30 '15 at 20:12

1 Answers1

0

The UserManager is registered with the built-in dependency injection. You can add

UserManager<ApplicationUser> userManager

to the constructor of the consuming class, and you should be able to use it. Assuming ASP.NET is responsible for the construction of that class.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
GavKilbride
  • 1,409
  • 15
  • 19