0

I am currently using DI for my context like below.

services.AddTransient<APDatabase.DBContext>(provider =>
{
    return new APDatabase.DBContext();
});

Is it possible to pass the current logged in user into this? I currently get the user in the controller as follows.

public NavigationController(APDatabase.DBContext context, IHttpContextAccessor httpContextAccessor)
{
    this._context = context;
    this._currentUser = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
}

I could then set this as a property on the context in the contsructor of each controller. This is the only way I can see of doing this currently but would prefer to have the DI handle it for me if possible.

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
user3208483
  • 385
  • 5
  • 14
  • 1
    Possible duplicate of [How to get user information in DbContext using Net Core](https://stackoverflow.com/questions/36401026/how-to-get-user-information-in-dbcontext-using-net-core) – Shahzad Hassan Apr 29 '19 at 18:22
  • Also, please don't register the DbContext like you are. Use `Services.AddDbContext()` instead – Shahzad Hassan Apr 29 '19 at 19:04

1 Answers1

0

First, you should use DI to register the DBContext by services.AddDbContext<ApplicationDbContext> instead of return new APDatabase.DBContext();.

Follow steps below:

  1. DbContext:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        private HttpContext _httpContext;
        public string CurrentUser => _httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options,
            IHttpContextAccessor httpContextAccessor)
            : base(options)
        {
            _httpContext = httpContextAccessor.HttpContext;
        }        
    }
    
  2. Register DbContext

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    
  3. UseCase

    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _appDbContext;
        public HomeController(ApplicationDbContext applicationDbContext)
        {
            _appDbContext = applicationDbContext;
        }        
        public async Task<IActionResult> Index()
        {
            var user = _appDbContext.CurrentUser;
            return View();
        }
    
    }
    
Edward
  • 28,296
  • 11
  • 76
  • 121