Actually there are two errors? in Autofac that cause this behavior:
Mistake # 1: As a side effect of fixing Problem 351 AutofacDependencyResolver needs to be registered in the generated LifeTimeScope s request. MVC interaction does this, but Winforms integration certainly does not.
error? # 2: Both RequestLifetimeScopeProvider and ContainerProvider save the created ILifetimeScope with the same HttpContext.Current.Items key:
static ILifetimeScope LifetimeScope { get { return (ILifetimeScope)HttpContext.Current.Items[typeof(ILifetimeScope)]; } set { HttpContext.Current.Items[typeof(ILifetimeScope)] = value; } }
So, there is a bit of a race condition, because depending on which module will be executed, WebForms or MVC Intergartion ILifetimeScope first wins. Therefore, if the WebForms module wins the AutofacDependencyResolver , it will not be registered, and you will get a beautiful exception exception.
Fix / workaround:
But there is a simple workaround: you just need to register the AutofacDependencyResolver in the ContainerProvider requestLifetimeConfiguration , so no matter which one wins (WebForm vs. MVC), AutofacDependencyResolver will always be registered:
var autofacDependencyResolver = new AutofacDependencyResolver(container); DependencyResolver.SetResolver(autofacDependencyResolver); _containerProvider = new ContainerProvider(container, requestContainerBuilder => requestContainerBuilder.RegisterInstance(autofacDependencyResolver) .As<AutofacDependencyResolver>());
source share