In ASP Identity Framework 2 UserManager has sync wrappers for many of its async methods. Unfortunately this sync wrappers are using AsyncHelper, say FindById(...):
return AsyncHelper.RunSync(() => manager.FindByIdAsync(userId));
Examining the RunSync method it turns out it runs the method in an other thread:
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
var cultureUi = CultureInfo.CurrentUICulture;
var culture = CultureInfo.CurrentCulture;
return _myTaskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap().GetAwaiter().GetResult();
}
However in this other thread the HttpContext.Current will be null, because it is thread local. Unfortunately the ASP Identity Framework 2 relies on HttpContext.Current, for example the Seed method calls InitializeIdentityForEF, which tries to access the context this way, and throws a null reference exception:
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
//Create User=Admin@Admin.com with password=Admin@123456 in the Admin role
// ReSharper disable once InconsistentNaming
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
My main question: How can I call the UserManager's (or others) async methods without risking to marshalled to an other thread, where HttpContext.Current will be null, which can cause unexpected behavior (within the identity framework itself)? Obviously the provided sync wrappers are unusable.
Before someone are asking why I would like to call in sync: Say I would like to use UserManager in a property get, where await is not an option. Besides of this the sync wrappers do exist (for a reason I think) just unusable, or at least introduce the worst kind of bug: a random null in random places.