在异常过滤器中访问DbContext

3

我编写了一个ExceptionFilter属性,在其中需要访问dbContext类进行数据库操作。但是在我的筛选器属性中收到null引用。

是否有任何方法可以获得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();
        }
    }

我需要提醒的是,这是一个ASP.NET Core应用程序。

1个回答

3

您可以从ExceptionContext中访问IServiceProvider

public override async Task OnExceptionAsync(ExceptionContext context)
{
    var db = context.HttpContext.RequestServices.GetService<AppIdentityDbContext>();

    ...

    await db.SaveChangesAsync();
}

1
非常感谢!虽然在我的情况下GetService方法是这样的:var db = context.HttpContext.RequestServices.GetService(typeof(AppIdentityDbContext)); - Reza EN
1
通用扩展方法 GetService<T>()GetRequiredService<T>() 位于 Microsoft.Extensions.DependencyInjection 命名空间中。 - Brad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接