Thank you for your feedback,
but adding <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> did not help.
- If you hit the breakpoint after the async call in the controller's action but it blows up before returning from the method then that would seem to indicate an issue either in the runtime --> The exception is triggered before returning to the caller (Controller) and it's not handled by the try/catch block
- This issue appears to be limited to calls to one specific method FirstOrDefaultAsync (MongoDB C# driver)
- _collection.Find(predicate).FirstOrDefaultAsync().Result; works without triggering any exception. _collection?.Find(predicate).FirstOrDefaultAsync() ?? null; does not
- Both methods return the expected value, then something weird happens in case of the async one
I had a look at the implementation of FirstOrDefaultAsync:
public static async Task<TDocument> FirstOrDefaultAsync<TDocument>(this IAsyncCursor<TDocument> cursor, CancellationToken cancellationToken = default(CancellationToken))
{
using (cursor)
{
var batch = await GetFirstBatchAsync(cursor, cancellationToken).ConfigureAwait(false);
return batch.FirstOrDefault();
}
}
where GetFirstBatchAsync is:
private static async Task<IEnumerable<TDocument>> GetFirstBatchAsync<TDocument>(IAsyncCursor<TDocument> cursor, CancellationToken cancellationToken)
{
if (await cursor.MoveNextAsync(cancellationToken).ConfigureAwait(false))
{
return cursor.Current;
}
else
{
return Enumerable.Empty<TDocument>();
}
}
So there shouldn't be anything in my code / MongoDB driver that could cause that null reference exception.
The lack of a stack trace seems to tell me that the issue happens actually inside the runtime (or within the DI: Castle.Windsor 5.1.x, for some obscure reasons)