Skip to content

Instantly share code, notes, and snippets.

@cherrydev
Created April 30, 2015 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cherrydev/5c7168c8947eb1a1b5b8 to your computer and use it in GitHub Desktop.
Save cherrydev/5c7168c8947eb1a1b5b8 to your computer and use it in GitHub Desktop.
Creating a testable service that accesses the current ClaimsPrincipal
public interface ICurrentPrincipalAccessor {
ClaimsPrincipal CurrentPrincipal { get; }
}
public class HttpContextCurrentPrincipalAccessor : ICurrentPrincipalAccessor {
private IHttpContextAccessor _httpContextAccessor;
public HttpContextCurrentPrincipalAccessor(IHttpContextAccessor httpContextAccessor) {
_httpContextAccessor = httpContextAccessor;
}
public ClaimsPrincipal CurrentPrincipal { get { return _httpContextAccessor.HttpContext.User; } }
}
// In Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services) {
// everything else...
services.AddSingleton<ICurrentPrincipalAccessor, HttpContextCurrentPrincipalAccessor>();
}
// In your service class
public class MyTestableServiceClass {
private ICurrentPrincipalAccessor _currentPrincipalAccessor;
public MyTestableServiceClass(ICurrentPrincipalAccessor currentPrincipalAccessor) {
_currentPrincipalAccessor = currentPrincipalAccessor;
}
public void MyServiceMethod() {
var userId = _currentPrincipalAccessor.CurrentPrincipal.GetUserId();
// ... etc
}
}
@gruckion
Copy link

gruckion commented May 13, 2018

How do I access _currentPrincipalAccessor from my DbContext? So I can apply _currentPrincipalAccessor.CurrentPrincipal.GetUserId() to the Auditable information when persisting the data to a db.

I just placed _currentPrincipalAccessor in my DbContext and it worked out fine. I am also using IDesignTimeDbContextFactory, but this uses a second constructor which does not assign a value to the instance _currentPrincipalAccessor. Since the IdesignTimeDbContextFactory will not me making any changes to the database it should be fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment