title: EF Switch between different contexts of same type
body: <p>I have a mulitenant application, which has multiple databases for different customers having same db structure. </p>
  
  <p>In application, after user logs in based on his customer-id I will know connection string for his customer database and after his login button click event I will need to change my db context dynamically on the fly.</p>
  
  <p>I am using EF 5.0 and Autofac IOC container.
  I have pasted my code here which is not helping me.</p>
  
  <p>Whats the best way I can manage this?</p>
  
  <pre><code>        string EntityFrameworkConnectionString = null;
          var builder = new ContainerBuilder();
  
          builder.Register(c =&gt;
          {
              if (string.IsNullOrEmpty(EntityFrameworkConnectionString))
              {
                  var profileProvider = c.Resolve&lt;IConfigurationProfileProvider&lt;CustomerProfile&gt;&gt;();
                  var profile = profileProvider.GetProfile();
                  EntityFrameworkConnectionString = profile.CustomerDatabaseConnectionString;
              }
              return new CustomerDataContext(EntityFrameworkConnectionString);
          })
          .As&lt;ICustomerDataContext&gt;()
          .As&lt;IDbContext&gt;()
          .InstancePerDependency();
  
          builder.RegisterType&lt;CustomerDataContextFactory&gt;().As&lt;ICustomerDataContextFactory&gt;();
  
          var assembly = Assembly.GetExecutingAssembly();
          builder.RegisterAssemblyTypes(assembly)
                 .Where(t =&gt; t.Name.EndsWith("Repository"))
                 .AsImplementedInterfaces()
                 .InstancePerDependency();
  </code></pre>