【问题标题】:Lifetime scopes with Lazy Initialization?具有延迟初始化的生命周期范围?
【发布时间】:2016-03-24 15:09:19
【问题描述】:

我找不到任何关于如何将 Autofac 与 Lazy 和生命周期范围一起使用的文档。得到一个关于

的错误

"从范围中看不到具有与“事务”匹配的标记的范围 请求实例的位置..."

在我的控制器构造函数中:

public HomeController(Lazy<ISalesAgentRepository> salesAgentRepository, Lazy<ICheckpointValueRepository> checkpointValueRepository)
{

       _salesAgentRepository = new Lazy<ISalesAgentRepository>(() => DependencyResolver.Current.GetService<ISalesAgentRepository>());
       _checkpointValueRepository = new Lazy<ICheckpointValueRepository>(() => DependencyResolver.Current.GetService<ICheckpointValueRepository>());
}

在我的行动中:

using (var transactionScope = AutofacDependencyResolver.Current.ApplicationContainer.BeginLifetimeScope("transaction"))
{
   using (var repositoryScope = transactionScope.BeginLifetimeScope())
   {
         // ....
   }
}

生命周期范围与 Lazy 不兼容还是我完全弄错了?

【问题讨论】:

    标签: c# asp.net-mvc dependency-injection autofac lazy-initialization


    【解决方案1】:

    是的,你找错树了。

    为每个新的应用程序请求创建一个新控制器。因此无需尝试单独管理依赖项的生命周期。

    将您的存储库配置为具有范围生命周期。对事务范围执行相同操作。

    完成后,两个存储库将拥有相同的共享事务范围。

    您还可以将事务提交移至操作过滤器,如下所示:

    public class TransactionalAttribute : ActionFilterAttribute
    {
        private IUnitOfWork _unitOfWork;
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null)
                _unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();
    
            base.OnActionExecuting(filterContext);
        }
    
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null && _unitOfWork != null)
                _unitOfWork.SaveChanges();
    
            base.OnActionExecuted(filterContext);
        }
    }
    

    (将IUnitOfWork 替换为事务范围)。来源:http://blog.gauffin.org/2012/06/05/how-to-handle-transactions-in-asp-net-mvc3/

    【讨论】:

    • 如果是 web api 过滤器。从上下文中解决它。 filterContext.Request.GetDependencyScope().GetService(typeof(IUnitOfWork)) as IUnitOfWork。否则它将从根容器解析,并且不会是请求中的同一个实例。因为 web api 过滤了缓存的单例。
    猜你喜欢
    • 2016-11-03
    • 2023-03-03
    • 2019-02-08
    • 2015-03-22
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    相关资源
    最近更新 更多