I've written an ExceptionFilter attribute which in that i need to access dbContext class to do database affairs. but i receive null reference in my filter attribute.
Is there any way that i can get working reference of dbContext?
public class AppExceptionAttribute : ExceptionFilterAttribute
{
AppIdentityDbContext _context;
public AppExceptionAttribute(AppIdentityDbContext context)
{
_context = context;
}
public AppExceptionAttribute()
{ }
public override async Task OnExceptionAsync(ExceptionContext context)
{
var exception = context.Exception;
while (exception != null)
{
//here _context is null, that is a dbContext class
_context.Errors.Add(new Entities.Error {
Message = exception.Message,
StackTrace = exception.StackTrace,
Date = DateTime.Now
});
exception = exception.InnerException;
}
await _context.SaveChangesAsync();
}
}
i need to mention that is an asp.net core application
You can access the IServiceProvider from the ExceptionContext.
public override async Task OnExceptionAsync(ExceptionContext context)
{
var db = context.HttpContext.RequestServices.GetService<AppIdentityDbContext>();
...
await db.SaveChangesAsync();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With