Injecting ClaimsPrincipal into Service / Business logic – layers (.NET Core)

So… You want to add authorization or atleast being able to figure out the username in the business logic layer.
What i’ve previously done is inject the username from the ui layer into the service-layer through input params on all methods (bad).
To inject the claimsprincipal in .NET Core we utilize the builtin IOC capabilities and simply
services.AddTransient(s => s.GetService().HttpContext.User); in Startup.cs
with the above we can simply just state (in the constructor) that our service / class / what ever needs a ClaimsPrincipal

Note: This requires the user is authenticated AND that you are using Claims (obviously).

Building on this, we could do something like the following;
Create a new service interface something like ICurrentUserProvider, with a method like public YourUserModel GetCurrentUser().

Implement the provider, injecting ClaimsPrincipal, your DbContext and maybe a caching service.

The convert the ClaimsPrincipal to your YourUserModel save it to the cache and return it.

Easy, simple HttpRuntime.Cache

A simple to use caching function that both gets and/or sets the key depending on results.

This is a post for my future self. – Hi future self! (wave).
The following is an easy to use caching function.

The function gets or updates based on results.
The wrapper helps create different cacheExpirations based on needs.