4

Default ASP.NET MVC5 template with user authentication is registering services with app.CreatePerOwinContext. Like:

app.CreatePerOwinContext<DbContext>(DbContext.Create)
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create)

And then in many places we can see just service locator pattern(or anti-pattern):

UserManager = _userManager ?? HttpContext.GetOwinContext().Get<ApplicationUserManager>();

It makes code untestable and extending eg. ApplicationUserManager by injecting to it some custom service of course also needs service location.

Can I totally get rid of this code by using IoC container like Autofac, Ninject etc? I mean i would delete app.CreatePerOwinContext stuff, and register it in IoC container I use. Then I would just normally inject them to controllers/service by constructor injection.

Would it be fine to replace app.CreatePerOwinContext with just container.Register and then setting my container as a defaultdependency resolver?

monoh_
  • 1,019
  • 3
  • 13
  • 15
  • I think you should be able to do this. I tried a while ago, but ran into some issues with EF caching data (see http://stackoverflow.com/questions/29170366/aspnet-identity-caching-with-dependency-injection). I don't recall resolving that issue, so I'm interested to see what others think. – Kevin Kuszyk Sep 14 '16 at 15:14

0 Answers0