asp.net-mvc – UnitOfWork in Action Filter似乎是缓存

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – UnitOfWork in Action Filter似乎是缓存前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用IoC(Unity)的MVC 3网站,我的模型是与EF4和POCO一起生成的.我正在使用一个动作过滤器来提交我的UnitOfWork:
public class UseUnitOfWorkAttribute : ActionFilterAttribute,IActionFilter
{
    private readonly IUnitOfWork _unitOfWork;

    public UseUnitOfWorkAttribute()
    {
        _unitOfWork = IoCFactory.Instance.CurrentContainer.Resolve<IUnitOfWork>();
    }

    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        _unitOfWork.Commit();
    }

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
    }
}

但是,即使Commit()似乎被触发了,它似乎在缓存它认为是“脏”的.

例如,在我的控制器中,以下操作从服务类执行:

var user = _userRepository.Single(u => u.Id == 2);
user.DateAdded = DateTime.Now;

每当我做一个新的解决方案的构建并且击中这个控制器动作,这个改变实际上是提交的.然而,对控制器的连续命中并不做任何事情.

另一方面,如果我将一个UnitOfWork放在我的控制器中,并按照服务方法调用进行提交,它将按预期的方式工作(每当我请求控制器操作时):

public AccountController()
{
    _unitOfWork = IoCFactory.Instance.CurrentContainer.Resolve<IUnitOfWork>();
}

public ActionResult Test()
{
    var user = _userRepository.Single(u => u.Id == 2);
    user.DateAdded = DateTime.Now;
    _unitOfWork.Commit();
}

所以看起来好像有些缓存正在进行,但是我无法弄清楚缓存是什么 – UnitOfWork,ActionFilter或者存储库.

任何想法可能会发生什么?如果没有,任何想法我可以做什么来排除故障?

提前致谢.

解决方法

您正在动作过滤器的构造函数中初始化您的工作单元,这意味着在动作过滤器被实例化时将被注入.报价从 ASP.NET MVC 3 release notes

In prevIoUs versions of ASP.NET MVC,action filters were created per request except in a few cases. This behavior was never a guaranteed behavior but merely an implementation detail and the contract for filters was to consider them stateless. In ASP.NET MVC 3,filters are cached more aggressively. Therefore,any custom action filters which improperly store instance state might be broken.

原文链接:https://www.f2er.com/aspnet/250043.html

猜你在找的asp.Net相关文章