Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediatR - Handling current user in query

What is the best way to model the current user in a query? I'm creating a razor page application. I need to be able to attach the current user when I am executing queries and commands. Is there a recommended approach for doing this?

like image 353
Zeus82 Avatar asked Dec 18 '22 20:12

Zeus82


1 Answers

The below approach works well for me as I have the get the user into a service layer that my Razor projects depend on.

As per the guidance by David Fowler here, I created a UserAccessor class as follows:

public interface IUserAccessor { ClaimsPrincipal User { get; } }

public class UserAccessor : IUserAccessor
{
    private readonly IHttpContextAccessor _accessor;

    public UserAccessor(IHttpContextAccessor accessor)
    {
        _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
    }

    public ClaimsPrincipal User => _accessor.HttpContext.User;
}

which I register in my Razor project on startup by calling

services.AddTransient<IUserAccessor, UserAccessor>()

and then inject that into the MediatR handlers and my DbContext as well as some factories as required.

private readonly IUserAccessor _userAccessor;

public EventLogFactory(IUserAccessor userAccessor)
{
    _userAccessor = userAccessor ?? throw new ArgumentNullException(nameof(userAccessor));
} 

The IHttpContextAccessor referenced in UserAccessor requires the Microsoft.AspNetCore.Http.Abstractions nuget in projects that don't reference Microsoft.AspNetCore.App meta package and will also require that your Razor project implements AddHttpContextAccessor()on startup as well:

// Register IHttpContextAccessor for services to get access to the HttpContext.  
services.AddHttpContextAccessor();

Hope this helps.

like image 149
Chris.ZA Avatar answered Feb 25 '23 04:02

Chris.ZA