I’ve been following several tutorial on integrating the OWin identity in my ASP.net app, for instance this one
So my StartupLogin now has the method
public static void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
[...]
to create (and I quote the link) “a per-request, single instance of the UserManager and DbContext classes from the OWIN context to be used throughout the application.”
But I saw very weird calling behavior to the Create functions, so I added the class
class DebugManager : IDisposable
{
private static int count = 0;
public static DebugManager Create() { Debug.WriteLine($"Owin Build called {count++};"); return new DebugManager(); }
public void Dispose() { }
}
and the line
app.CreatePerOwinContext(DebugManager.Create);
Looking at the debug window, I saw that the Create() methods are called 74 times on initial application startup, and 120-124(!!!!) times on other actions like login, page refresh, logout, etc, etc…
That cannot be the way it should work, right? A create function should only be called once, where after you can get the instance of the object via the OWinContext.Get<>, right? What’s going on here?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I found the answer here
Dependency Injection in Owin
… each time the OwinContext is pulled from the HttpContext, it returns a new context … if we are applying DI terms here, then your object is registered in per-request scope, as you would expect to be DbContext.
And I recently learned the difference between “transient”, “scoped” and “singleton” in this answer.
It turns out a page request of our (very large) project (in development mode, where caching of static files is off) causes 125 requests to server, which caused the issue.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0