title: Selecting DbContext based on Entity with AutoFac
body: <p>I'm trying to specify which dbcontext to use based on entity with autofac. Below are my codes:</p>
  
  <p>Global.asax</p>
  
  <pre><code>foreach (var database in DatabaseManager.Databases)
              {
                  builder.Register&lt;IDbContext&gt;(c =&gt; new CodesObjectContext(database.ConnectionString, database.Alias)) //database.Alias is database name
                      .As&lt;IDbContext&gt;()
                      .Named&lt;IDbContext&gt;(database.Alias)
                      .InstancePerLifetimeScope();
              }
  builder.RegisterGeneric(typeof(EfRepository&lt;&gt;)).As(typeof(IRepository&lt;&gt;)).InstancePerLifetimeScope();
  </code></pre>
  
  <p>Is there anyway i can specify which dbcontext to pass to EfRepository?</p>
  
  <pre><code>public partial class EfRepository&lt;T&gt; : IRepository&lt;T&gt; where T : BaseEntity
      {
          private readonly IDbContext _context;
          private IDbSet&lt;T&gt; _entities;
  
          public EfRepository(IDbContext context)
          {
              this._context = context;
          }
  }
  </code></pre>
  
  <p>and in my entity i would have something like this</p>
  
  <pre><code>[DatabaseName("Database1")]
  public partial class SampleEntity : BaseEntity
  {
  }
  </code></pre>
  
  <p><strong>UPDATED</strong>
  Here is my objectcontext class</p>
  
  <pre><code>public class CodesObjectContext : DbContext, IDbContext
      {
          public virtual string DatabaseName { get; private set; }
          public CodesObjectContext(string nameOrConnectionString, string databaseName)
              : base(nameOrConnectionString)
          {
              DatabaseName = databaseName;
          }            
  }
  </code></pre>
  
  <p>So is there a way to match entity database attribute and context database name, then only pass this context to the repository constructor</p>