2017-04-26 135 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

相關問題