I have a baseDbContext like this:
public abstract class BaseDbContext : DbContext
{
private IHttpContextAccessor _contextAccessor;
private Guid tenantId => this.GetTenantId();
private Guid tenantCountryId => this.GetTenantCountryId();
private static MethodInfo ConfigureEntityDefaultsMethodInfo = typeof(BaseDbContext).GetMethod(nameof(ConfigureEntityDefaults), BindingFlags.Instance | BindingFlags.NonPublic);
public BaseDbContext() { }
public BaseDbContext(DbContextOptions<BaseDbContext> options, IHttpContextAccessor contextAccessor) : base(options)
{
_contextAccessor = contextAccessor;
}
public BaseDbContext(DbContextOptions options, IHttpContextAccessor contextAccessor) : base(options)
{
_contextAccessor = contextAccessor;
}
public BaseDbContext(DbContextOptions<HostDataContext> options, IHttpContextAccessor contextAccessor) : base(options)
{
_contextAccessor = contextAccessor;
}
Basically my service is calling the saveChangesAsync() method in this class :
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
ApplyBaseEntityActions();
return base.SaveChangesAsync(cancellationToken);
}
protected virtual void ApplyBaseEntityActions()
{
var userId = GetCurrentProfileId();
foreach (var entry in ChangeTracker.Entries().ToList())
{
switch (entry.State)
{
case EntityState.Added:
ApplyBaseEntityAddedActions(entry, userId);
break;
case EntityState.Modified:
ApplyBaseEntityUpdatedActions(entry, userId);
break;
case EntityState.Deleted:
ApplyBaseEntityDeletedActions(entry, userId);
break;
}
}
}
protected virtual Guid GetCurrentProfileId()
{
Guid result = Guid.Empty;
if (_contextAccessor != null && _contextAccessor.HttpContext != null)
{
result = _contextAccessor.HttpContext.GetProfileId();
}
return result;
}
But when it reaches GetCurrentProfileID the _contextAccessor is null and so I am getting empty Guid Value.
Edit : This is how I am injecting the httpcontetAccessor to my class which is calling dbContext :
public SellRateService(
EzyDataContext dbContext,
IConfiguration config,
IHttpContextAccessor contextAccessor, ILogger<SellRateService> logger,
IEmailHelper emailHelper )
{
_dbContext = dbContext;
_config = config;
_contextAccessor = contextAccessor;
_logger = logger;
_emailHelper = emailHelper;
}
and this in services :
services.AddHttpContextAccessor();
Can anyone please help on why the contextAccessor is null and and how should I remedy it.
Thanks.