title: Adding connection string to DBContext (NpgSQL, Dependency Injection, .NET Core)
body: <p>I am trying dynamically load up a connection string and inject it in to my DbContext inherited class.  I am not sure I am doing it correctly (can't get it to work anyway).</p>
  
  <p>My MyDbContext looks like this:</p>
  
  <pre><code>public class MyDbContext : DbContext
  {
      private readonly string _connectionString;
      public DbSet&lt;Things&gt; Things{ get; set; }
  
      public MyDbContext (string connectionString)
      {
          _connectionString = connectionString;
      }
  
  
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
          optionsBuilder.UseNpgsql(_connectionString);
      }
  
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
          modelBuilder.ForNpgsqlUseIdentityColumns();
      }
  }
  </code></pre>
  
  <p>My Startup, looks like this:</p>
  
  <pre><code>    public void ConfigureServices(IServiceCollection services)
      {
  
          services.AddEntityFrameworkNpgsql()
          .AddDbContext&lt;MyDbContext&gt;(s =&gt; new MyDbContext("Host=192.168.0.1; Port=4016;Database=Test;Username=test;Password=test"))
          .BuildServiceProvider();
  
          services.AddMvc();
  
          services.AddTransient&lt;DbContext, MyDbContext&gt;(s =&gt; new MyDbContext("Host=192.168.0.1; Port=4016;Database=Test;Username=test;Password=test"));
  
      }
  
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
  
          app.UseStaticFiles();
          app.UseCookiePolicy();
  
          app.UseMvc();
  
          using (var serviceScope = app.ApplicationServices.GetService&lt;IServiceScopeFactory&gt;().CreateScope())
          {
              var context = serviceScope.ServiceProvider.GetRequiredService&lt;MyDbContext&gt;();
              context.Database.Migrate();
          }
  
      }
  </code></pre>
  
  <p>The code throws an exception on the line within Configure(...):</p>
  
  <pre><code>var context = serviceScope.ServiceProvider.GetRequiredService&lt;MyDbContext&gt;();
  </code></pre>
  
  <p>The exception is:</p>
  
  <blockquote>
    <p>Application startup exception: System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'MyDbContext'.</p>
  </blockquote>