Created
April 30, 2015 01:04
-
-
Save cherrydev/5c7168c8947eb1a1b5b8 to your computer and use it in GitHub Desktop.
Creating a testable service that accesses the current ClaimsPrincipal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.