我找不到任何关于如何将Autofac与Lazy和lifetime作用域一起使用的文档。获取有关的错误
"从作用域中看不到标记匹配"transaction"的作用域请求的实例。。。"
在我的控制器构造函数中:
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不兼容,或者我完全弄错了?
为每个新的应用程序请求创建一个新的控制器。因此,不需要尝试单独管理依赖关系的生存期。
将存储库配置为具有作用域生存期。对事务范围执行同样的操作。
完成后,两个存储库将具有相同的共享事务范围。
您还可以将事务提交移动到操作过滤器,如下所示:
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);
}
}
(用transactionscope替换IUnitOfWork
)。来源:http://blog.gauffin.org/2012/06/05/how-to-handle-transactions-in-asp-net-mvc3/