title: Autofac with WCF - Nested lifetimes problems
body: <p>I have a number of WCF services setup which are consumed by angularjs. Currently I've run into a problem that I'm struggling with. I keep receiving the following error message when calling the WCF services. Any pointers on how to fix the issue would be appreciated. A more detailed error message can be found at the bottom</p>
  
  <blockquote>
    <p>Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.</p>
  </blockquote>
  
  <p><strong>Edit: It seems to work when I build the container in global.asax Application_BeginReques() also, hence not only Application_Start. No clue why but at least this is better than before.... However I've previously had this error occur every now and then so I don’t trust this ugly work-around</strong></p>
  
  <p>Here is my global.asax</p>
  
  <pre><code>        ..
          ..
  
      protected void Application_Start(object sender, EventArgs e)
      {
          var containerBuilder = new IoC();
  
          // Register your service implementations.
          containerBuilder.Builder.RegisterType&lt;Konstrukt.SL.Services.GetBudgetData&gt;().Named&lt;object&gt;("GetBudgetDataService");
          containerBuilder.Builder.RegisterType&lt;Konstrukt.SL.Services.GetReferenceData&gt;().Named&lt;object&gt;("GetReferenceDataService");
          containerBuilder.Builder.RegisterType&lt;Konstrukt.SL.Services.UpdateBudgetData&gt;().Named&lt;object&gt;("UpdateBudgetDataService");
          ..
          ..
          containerBuilder.Builder.RegisterType&lt;Konstrukt.SL.Services.DimValue&gt;().Named&lt;object&gt;("DimValueService");
          containerBuilder.Builder.RegisterType&lt;Konstrukt.SL.Services.DisplayNameMapping&gt;().Named&lt;object&gt;("DisplayNameMappingService");
          ..
          ..
  
          // use only one context object per scope/request
          containerBuilder.Builder.RegisterType&lt;Konstrukt.DAL.KonstruktEntities&gt;().InstancePerLifetimeScope();
  
          AutofacHostFactory.Container = containerBuilder.Builder.Build();
      }
  </code></pre>
  
  <p>Here is my IoC class which registeres all the interfaces</p>
  
  <pre><code>public class IoC
  {
      private ContainerBuilder _builder;
      public ContainerBuilder Builder 
      {
          get 
          {
              if (_builder == null)
              {
                  _builder = new ContainerBuilder();
  
                  _builder.RegisterType&lt;BL.App.App&gt;().As&lt;BL.App.IApp&gt;();
                  _builder.RegisterType&lt;BL.AppConfig.AppConfig&gt;().As&lt;BL.AppConfig.IAppConfig&gt;();
                  _builder.RegisterType&lt;BL.AppConfig.ComponentSetting&gt;().As&lt;BL.AppConfig.IComponentSetting&gt;();
                  _builder.RegisterType&lt;BL.AppConfig.Component&gt;().As&lt;BL.AppConfig.IComponent&gt;();
                  _builder.RegisterType&lt;BL.AppConfig.AppSetting&gt;().As&lt;BL.AppConfig.IAppSetting&gt;();
                  _builder.RegisterType&lt;BL.AppConfig.AppDataSet&gt;().As&lt;BL.AppConfig.IAppDataSet&gt;();
                  _builder.RegisterType&lt;BL.AppConfig.AttributeData&gt;().As&lt;BL.AppConfig.IAttributeData&gt;();
                  _builder.RegisterType&lt;BL.AppConfig.Constants&gt;().As&lt;BL.AppConfig.IConstants&gt;();
                  ..
                  ..
                  _builder.RegisterType&lt;BL.DimensionData.DisplayNameMapping&gt;().As&lt;BL.DimensionData.IDisplayNameMapping&gt;();
                  ..
                  ..
                  //DAL registrations, etc
                  ..
                  ..
  
              }
              return _builder;
          }
          set { _builder = value; }
      }
  
  }
  </code></pre>
  
  <p>Sample WCF service implementation</p>
  
  <pre><code>public class DimValue : IDimValue
  {
      private BL.DimensionData.IDimValue _dimValue;
      public DimValue(ILifetimeScope container, BL.DimensionData.IDimValue dimValue)
      {
          AutofacHostFactory.Container = container;
          _dimValue = dimValue;
      }
  
      public IList&lt;Shared.Poco.DimValue&gt; GetDimValueList(int budgetId, string dimensionFilterJSON, string userId)
      {
          Dictionary&lt;Shared.Poco.Dimension, List&lt;string&gt;&gt; dimensionFilters = null;
          Shared.Poco.User user = new Shared.Poco.User { UserId = userId };
          IList&lt;Shared.Poco.DimValue&gt; list = new List&lt;Shared.Poco.DimValue&gt;();
  
          using (var scope = AutofacHostFactory.Container.BeginLifetimeScope())
          {
              dimensionFilters = JsonConvert.DeserializeObject&lt;Dictionary&lt;Shared.Poco.Dimension, List&lt;string&gt;&gt;&gt;(dimensionFilterJSON);
  
              foreach (KeyValuePair&lt;Shared.Poco.Dimension, List&lt;string&gt;&gt; kvp in dimensionFilters)
              {
                  foreach (Shared.Poco.DimValue dv in _dimValue.GetDimValueList(budgetId, kvp.Key, kvp.Value, user))
                  {
                      list.Add(dv);
                  }
              }
          }
          return list;
      }
  }
  
  [ServiceContract]
      public interface IDimValue
      {
          [OperationContract]
          [WebInvoke(Method = "GET",
                      RequestFormat = WebMessageFormat.Json,
                      ResponseFormat = WebMessageFormat.Json,
                      BodyStyle = WebMessageBodyStyle.Bare,
                      UriTemplate = "GetDimValueList?budgetId={budgetId}&amp;dimensionFilterJSON={dimensionFilterJSON}&amp;userId={userId}")]
          IList&lt;Shared.Poco.DimValue&gt; GetDimValueList(int budgetId, string dimensionFilterJSON, string userId);
      }
  </code></pre>
  
  <p>service markup</p>
  
  <pre><code>&lt;%@ ServiceHost Language="C#" 
  Debug="true" 
  Service="DimValueService"
  Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" 
  CodeBehind="DimValue.svc.cs" %&gt;
  </code></pre>
  
  <p>Detailed error when calling DimValue.svc/GetDimValueList</p>
  
  <blockquote>
    <p>The server encountered an error processing the request. The exception message is 'Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.'. See server logs for more details. The exception stack trace is: at Autofac.Core.Lifetime.LifetimeScope.CheckNotDisposed() at Autofac.Core.Lifetime.LifetimeScope.BeginLifetimeScope(Object tag) at Autofac.Core.Lifetime.LifetimeScope.BeginLifetimeScope() at Autofac.Integration.Wcf.AutofacInstanceContext..ctor(ILifetimeScope container) at Autofac.Integration.Wcf.AutofacInstanceProvider.GetInstance(InstanceContext instanceContext, Message message) at System.ServiceModel.Dispatcher.InstanceBehavior.GetInstance(InstanceContext instanceContext, Message request) at System.ServiceModel.InstanceContext.GetServiceInstance(Message message) at System.ServiceModel.Dispatcher.InstanceBehavior.EnsureServiceInstance(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</p>
  </blockquote>