简体   繁体   English

延迟初始化的生存期范围?

[英]Lifetime scopes with Lazy Initialization?

I can't find any documentation on how to use Autofac together with Lazy and lifetime scopes. 我找不到有关如何将Autofac与Lazy和Lifetime范围一起使用的任何文档。 Getting an error about 收到有关的错误

"No scope with a Tag matching 'transaction' is visible from the scope in which the instance was requested..." “从请求实例的范围中看不到带有匹配“事务”的标签的范围...”

In my Controller constructor: 在我的Controller构造函数中:

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

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

In my Action: 在我的动作中:

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

Are lifetime scopes incompatible with Lazy or did I got it completely wrong? 终身范围是否与Lazy不兼容,还是我完全错了?

Yes, you are barking up the wrong tree. 是的,您正在吠错树。

A new controller is created for every new application request. 为每个新的应用程序请求创建一个新的控制器。 Hence no need to try to manage the lifetime of the dependencies separately. 因此,无需尝试单独管理依赖项的生存期。

Configure your repositories to have a scoped lifetime. 将您的存储库配置为具有一定范围的生命周期。 Do the same for the transaction scope. 对事务范围执行相同的操作。

When done both repositories will have the same shared transactionScope. 完成后,两个存储库将具有相同的共享transactionScope。

You can also move the transaction commit to an action filter, like this: 您还可以将事务提交移至操作过滤器,如下所示:

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);
    }
}

(replace IUnitOfWork with transactionscope). (用transactionscope替换IUnitOfWork )。 Source: http://blog.gauffin.org/2012/06/05/how-to-handle-transactions-in-asp-net-mvc3/ 来源: http//blog.gauffin.org/2012/06/05/how-to-handle-transactions-in-asp-net-mvc3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM