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 MongoDB example, I need to pass the connection string. but I don't want to get it from the config-server every time.
Read some tutorials from here about dependency injection, not sure if this is really what I need.
Here is my tryout code..
my configservice that I want to setup or act as getter/setter
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()
}
}
MongdbContext that I want to fill the MongoUrl from the Configctl without getting from the Configctl each time.
public class MongdbContext<T> : 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");
}
}
and for experiment, I tried calling Configctl from ConfigureServices. I maybe wrong..
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new Configctl());
services.AddMvc();
}