ApplicationUserManager.Create called on every request
No sure if this is still open, but... I also didn't like the way the ApplicationUserManager was called each time, so I decided to change it to a singleton.
The object's dispose method is automatically called, unless you also pass in a destructor callback when you pass in the create.
So my ApplicationUserManager now looks like this:
public class ApplicationUserManager : UserManager<SmartUser, Guid>{ //This manager seems to get re-created on every call! So rather keep a singleton... private static ApplicationUserManager _userManager; private ApplicationUserManager(IUserStore<SmartUser, Guid> store) : base(store) { } internal static void Destroy(IdentityFactoryOptions<ApplicationUserManager> options, ApplicationUserManager manager) { //We don't ever want to destroy our singleton - so just ignore } internal static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { if (_userManager == null) { lock (typeof(ApplicationUserManager)) { if (_userManager == null) _userManager = CreateManager(options, context); } } return _userManager; } private static ApplicationUserManager CreateManager(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { ... your existing Create code ... }}
And in Startup.Auth, I pass in the Destroy callback
app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create, ApplicationUserManager.Destroy); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
Another option would be to just ignore the "registration code that is called per request" and make the UserStore a singleton....
No downside found yet with this heavier-handed approach...
Personally, using CreatePerOwinContext is definitely not recommended in this case. You should be only initializing the DbContext, UserManager and SignInManager once, and letting EF and MVC determine when a new context is necessary. MVC 5 and newer uses Dependency Injection (DI) more effectively, thus negating the need to having individual instances per context.
Only when you have code that should be considered critical and require a new context should you do so in that specific section of code, and not site-wide.