Reputation: 25955
I can't find any documentation on how to use Autofac together with Lazy and lifetime scopes. 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:
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?
Upvotes: 0
Views: 1047
Reputation: 101150
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.
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). Source: http://blog.gauffin.org/2012/06/05/how-to-handle-transactions-in-asp-net-mvc3/
Upvotes: 5