title: How to setup database connections only once from startup in .NET Core?
body: <p>I am newbiew in dotnet/c# and trying to learn. I am writing a server app that connects/init to different database. one is MongoDB. then I have a config microservice. how do I save the connection string that I got from my config-server? from these <a href="http://mongodb.github.io/mongo-csharp-driver/2.4/getting_started/quick_tour/" rel="nofollow noreferrer">MongoDB example</a>, I need to pass the connection string. but I don't want to get it from the config-server every time.</p>
  
  <p>Read some tutorials from <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection" rel="nofollow noreferrer">here</a> about dependency injection, not sure if this is really what I need.</p>
  
  <p>Here is my tryout code..</p>
  
  <p>my configservice that I want to setup or act as getter/setter</p>
  
  <pre><code>public class Configctl : IDisposable
  {
      public static string env;
      public Configctl()
      {
          env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
          Console.WriteLine($"ASPNETCORE_ENVIRONMENT/env={env}");
      }
  
      public static void ConfigureMongodb()
      {
          Console.WriteLine($"configure mongodb..");
          // var config = await getConfig()
      }
  }
  </code></pre>
  
  <p><code>MongdbContext</code> that I want to fill the <code>MongoUrl</code> from the <code>Configctl</code> without getting from the <code>Configctl</code> each time.</p>
  
  <pre><code>public class MongdbContext&lt;T&gt; : IDisposable
  {
      public IMongoDatabase _database { get; }
      public IMongoClient _client;
      public MongdbContext()
      {
          var settings = MongoClientSettings.FromUrl(GetMongoURL());
          _client = new MongoClient(settings);
          _database = _client.GetDatabase("testdb");
      }
  
      public void Dispose()
      {
          Console.WriteLine("mongodb disposed");
      }
  
      public static MongoUrl GetMongoURL()
      {
          return new MongoUrl("mongodb://user:pass@host:27017/admin");
      }
  }
  </code></pre>
  
  <p>and for experiment, I tried calling <code>Configctl</code> from <code>ConfigureServices</code>. I maybe wrong..</p>
  
  <pre><code>    public void ConfigureServices(IServiceCollection services)
      {
          services.AddSingleton(new Configctl());
  
          services.AddMvc();
      }
  </code></pre>