2016-10-24 70 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"); 
相关问题