2017-04-26 137 views
1

我是dotnet/c#中的newbiew并试图学习。我正在编写一个连接/ init到不同数据库的服务器应用程序。一个是MongoDB。那么我有一个配置微服务。我如何保存从配置服务器获得的连接字符串?从这些MongoDB example,我需要传递连接字符串。但我不想每次都从配置服务器获取它。如何在.NET Core中从启动时只设置一次数据库连接?

阅读here关于依赖注入的一些教程,不知道这是否真的是我需要的。

这里是我的试用代码..

我的ConfigService,我要设置或充当的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,我想,以填补从ConfigctlMongoUrl没有从获得Configctl每次。

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:[email protected]:27017/admin"); 
    } 
} 

和实验,我打过电话从ConfigureServicesConfigctl。我也许错了..

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddSingleton(new Configctl()); 

     services.AddMvc(); 
    } 

回答

2

如果你不需要从外部服务每次读选项,然后就看它在应用程序启动,绑定到POCO并注册POCO作为单。然后将POCO作为依赖项传递给您的MongdbContext

选项读者例如:

class OptionsReader 
{ 
    public MyOptions GetMyOptions() 
    { 
     //call to external config microservice, db, etc. 
    } 
} 

服务登记在启动类:

public void ConfigureServices(IServiceCollection services) 
{  
    services.AddTransient<OptionsReader>(); 
    services.AddSingletonFromService<OptionsReader, MyOptions>(x => x.GetMyOptions()); 
} 

有用extention方法:

public static void AddSingletonFromService<TService, TOptions>(
    this IServiceCollection services, 
    Func<TService, TOptions> getOptions) 
    where TOptions : class 
    where TService : class 
{ 
    services.AddSingleton(provider => 
    { 
     var service = provider.GetService<TService>(); 

     TOptions options = getOptions(service); 

     return options; 
    }); 
} 

选项消费者:

class MongdbContext 
{ 
    public MongdbContext(MyOptions options) 
    { 
    } 
} 
+0

这看起来很棒,很干净。我现在要试试这个。谢谢 – Hokutosei

+0

这帮了很大忙。谢谢 :) – Hokutosei

相关问题