asp.net MVC:当 ActionFilters 不是每个请求时,在自定义 AuthenticationAttribute 中使用 unitOfWork?

asp.net MVC : use unitOfWork inside custom AuthenticationAttribute when ActionFilters are not per-request?

我已经实施 IAuthenticationFilter 来创建一个自定义的。在 构造函数 中,我使用 structureMap 来获取 IUnitOfWork 的实例。此认证逻辑是检查数据库中的用户状态和....

IUnitOfWork uow;

public CustomAuthenticatationAttribute()
{
    this.uow = ObjectFactory.GetInstance<IUnitOfWork>();
}

我已经配置 structureMap 来服务 IUnitOfWork HttpContextScoped

x.For<IUnitOfWork>().HttpContextScoped().Use(() => new MyDbContext());

但随后发生了一些奇怪的事情。我在一个操作中删除了用户,但是当在另一个操作中执行 AuthenticationFilter 时,unitOfWork 的实例仍然 returns 用户!我在网上搜索了几个小时,然后来到这里:

Are ActionFilterAttributes reused across threads? How does that work?

简而言之,它表示过滤器被缓存并跨请求使用!

现在我很困惑。如何处理这个?我应该放弃使用 unitOfWork 并返回到 using(var context = ....) 吗?或者在过滤器中有使用 unitOfWork 的正确方法。

我在这里找到了解决方案

https://gist.github.com/ivanra/9019273

它取代了 DefaultFilterProvider,我希望尽可能避免使用它。

您在 FilterProvider 中找到的抑制缓存的解决方案实际上与 Autofac 和 Simple Injector 的 MVC 集成库使用的解决方案相同。

但是属性的缓存行为只是 one of the many reasons 为什么在属性中进行依赖注入实际上是一个坏主意。

如果可以的话,IMO 最好的解决方案是转向 passive attributes,或者至少将属性逻辑及其依赖项封装到一个组件中,除了在OnActionExecuting 方法。例如:

public class CustomAuthenticatationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var action =
            ObjectFactory.GetInstance<IActionFilter<CustomAuthenticatationAttribute>>();

        action.OnActionExecuting(this, context);
    }
}