public static IServiceCollection AddIdentityContext(this IServiceCollection services) { services.AddScoped <IIdentityContext, IdentityContext>(provider => { var httpCtxAccessor = provider.GetRequiredService <IHttpContextAccessor>(); var httpContext = httpCtxAccessor.HttpContext; if (httpContext is null) { return(IdentityContext.GetNewEmpty()); } var principal = httpCtxAccessor.HttpContext.User; if (!principal.IsAnyIdentityAuthenticated()) { return(IdentityContext.GetNewEmpty()); } var userId = principal.Claims .First(c => c.Type == ClaimTypes.NameIdentifier).Value; var identityContext = new IdentityContext(userId: userId); return(identityContext); }); return(services); }