title: Castle Windsor PerWebRequest Lifestyle is not being honored
body: <p>I'm working on a 3-tier MVC application. The data layer contains an EF4 code-first DbContext:</p>
  
  <pre><code>public class MyDataContext : DbContext
  {
      // DbSet&lt;&gt;s...
  }
  </code></pre>
  
  <p>There's also an interface and an implementation for DI:</p>
  
  <pre><code>public interface IContextFactory
  {
      MyDataContext GetContext();
  }
  
  public class ContextFactory : IContextFactory
  {
      readonly MyDataContext context;
      public ContextFactory(MyDataContext context)
      {
          this.context = context;
      }
  
      public MyDataContext GetContext()
      {
          return this.context;
      }
  }
  </code></pre>
  
  <p>And a repository pattern:</p>
  
  <pre><code>public interface IRepository&lt;T&gt;
  {
      T Create();
      void Insert(T entity);
      void Delete(T entity);
      ...
      void Save();
  }
  
  public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt;
    where TEntity: class, new()
  {
      public Repository(IContextFactory factory)
      {
          this.context = factory.GetContext();
          this.set = factory.Set&lt;TEntity&gt;();
      }
      ...
  }
  </code></pre>
  
  <p>The upper tiers access the entities by having <code>IRepository&lt;&gt;</code> injected with castle windsor. Custom providers/modules explicitly <code>.Resolve&lt;&gt;()</code> them as needed.</p>
  
  <p>The data layer is being registered in a castle <code>IWindsorInstaller</code>:</p>
  
  <pre><code>container.Register(
      Component.For&lt;MyDataContext&gt;()
      .DependsOn(new Hashtable() { {"connectionStringName", "DefaultConnection"} })
      .LifestylePerWebRequest());
  
  container.Register(
      Component.For&lt;IContextFactory&gt;()
      .ImplementedBy&lt;ContextFactory&gt;()
      .LifestylePerWebRequest());
  
  container.Register(
       Component.For(typeof(IRepository&lt;&gt;))
      .ImplementedBy(typeof(Repository&lt;&gt;))
      .LifestylePerWebRequest());
  </code></pre>
  
  <p>I wouldn't know anything was wrong - my tests don't cover the data context - but in debug mode my data context's constructor is getting called nearly a dozen times per web request.</p>
  
  <p><strong>edit</strong>: Whilst it does not explain why <code>Repository</code> and <code>MyDataContext</code> aren't getting scoped to web requests, my break point inside the constructor reveals an identical call stack all dozen-or-so times that its constructed: <code>MembershipProvider.GetUser -&gt; new Repository(IContextFactory)</code>. I have no explicit calls to <code>GetUser</code> - what in the world would cause FormsAuthentication to call GetUser so many times?</p>