2016-10-24 136 views
4

我試圖獲得連接字符串動態從appsettings.json文件。我看到我可以通過配置屬性啓動類。我已將配置字段標記爲靜態字段,並通過應用程序訪問它。在.NET核心應用程序中獲取連接字符串

我想知道是否有更好獲取連接字符串值的方法從.NET Core應用程序。

+0

您可以通過注入在ASP.NET核心的依賴注入的服務'Configuration'對象 - [實例點擊這裏](HTTPS:/ /radu-matei.github.io/blog/aspnet-core-configuration-greeting/#making-use-of-asp-net-core-dependency-injection) –

+1

如何將Configuration對象注入只有無參數構造函數的類?甚至我怎樣才能注入數據庫上下文到只有無參數構造函數的類? –

+0

至少在ASP.NET核心中,推薦的方法是使用考慮SoC和ISP原則的選項模式: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration#using-options -and-configuration-objects 這些原則也應該考慮用於.NET Core解決方案。 –

回答

5

您可以查看我的博客文章,關於ASP.NET Core Configuration here

其中我也通過配置選項的依賴注入。

報價:

有一對夫婦的方式來獲取設置。一種方法是在Startup.cs中使用 配置對象。

您可以通過在Startup.cs在ConfigureServices這樣做使你的應用程序可用的配置通過全球 依賴注入:

services.AddSingleton(配置);

+0

如何將Configuration對象注入只有無參數構造函數的類中?甚至我怎樣才能注入數據庫上下文到只有無參數構造函數的類? –

+0

感謝您的提示,我也是ASP.NET Core應用程序的初學者,不知道我們可以做這樣的事情。那很棒! – Eastrall

+2

@ A.Gladkiy具有默認IoC容器的ASP.NET Core DI僅使用構造函數注入。您不能以不同的方式將服務注入到類中。你應該看看其他人是否曾經問過這個問題,如果沒有,請問一個新的問題。 – juunas

0

您可以在Startup.cs文件中聲明的變量IConfiguration執行線程安全Singleton

private static object syncRoot = new object(); 
private static IConfiguration configuration; 
public static IConfiguration Configuration 
{ 
    get 
    { 
     lock (syncRoot) 
      return configuration; 
    } 
} 

public Startup() 
{ 
    configuration = new ConfigurationBuilder().Build(); // add more fields 
} 
0
private readonly IHostingEnvironment _hostEnvironment; 
    public IConfiguration Configuration; 
    public IActionResult Index() 
    { 
     return View(); 
    } 

    public ViewerController(IHostingEnvironment hostEnvironment, IConfiguration config) 
    { 
     _hostEnvironment = hostEnvironment; 
     Configuration = config; 
    } 

,並在課堂上要連接字符串

var connectionString = Configuration.GetConnectionString("SQLCashConnection"); 
相關問題