How to read connection string in .NET Core?











up vote
55
down vote

favorite
12












I want to read just a connection string from a configuration file and for this add a file with the name "appsettings.json" to my project and add this content on it:



{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-

WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}


On ASP.NET I used this:



 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;


Now how can I read "DefaultConnection" in C# and store it on a string variable in .NET Core?










share|improve this question
























  • docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
    – Ravi Teja
    Mar 10 '17 at 8:27















up vote
55
down vote

favorite
12












I want to read just a connection string from a configuration file and for this add a file with the name "appsettings.json" to my project and add this content on it:



{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-

WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}


On ASP.NET I used this:



 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;


Now how can I read "DefaultConnection" in C# and store it on a string variable in .NET Core?










share|improve this question
























  • docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
    – Ravi Teja
    Mar 10 '17 at 8:27













up vote
55
down vote

favorite
12









up vote
55
down vote

favorite
12






12





I want to read just a connection string from a configuration file and for this add a file with the name "appsettings.json" to my project and add this content on it:



{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-

WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}


On ASP.NET I used this:



 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;


Now how can I read "DefaultConnection" in C# and store it on a string variable in .NET Core?










share|improve this question















I want to read just a connection string from a configuration file and for this add a file with the name "appsettings.json" to my project and add this content on it:



{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-

WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}


On ASP.NET I used this:



 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;


Now how can I read "DefaultConnection" in C# and store it on a string variable in .NET Core?







c# connection-string asp.net-core-1.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 12 at 8:39









Harsh Patel

3219




3219










asked Aug 22 '16 at 15:26









motevalizadeh

1,39553565




1,39553565












  • docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
    – Ravi Teja
    Mar 10 '17 at 8:27


















  • docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
    – Ravi Teja
    Mar 10 '17 at 8:27
















docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
– Ravi Teja
Mar 10 '17 at 8:27




docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
– Ravi Teja
Mar 10 '17 at 8:27












5 Answers
5






active

oldest

votes

















up vote
44
down vote



accepted










You can do this with the GetConnectionString extension-method:



string conString = Microsoft
.Extensions
.Configuration
.ConfigurationExtensions
.GetConnectionString(this.Configuration, "DefaultConnection");

System.Console.WriteLine(conString);


or with a structured-class for DI:



public class SmtpConfig
{
public string Server { get; set; }
public string User { get; set; }
public string Pass { get; set; }
public int Port { get; set; }
}


Startup:



public IConfigurationRoot Configuration { get; }


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
// services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));


And then in the home-controller:



public class HomeController : Controller
{

public SmtpConfig SmtpConfig { get; }
public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
{
SmtpConfig = smtpConfig.Value;
} //Action Controller


public IActionResult Index()
{
System.Console.WriteLine(SmtpConfig);
return View();
}


with this in appsettings.json:



"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},

"Smtp": {
"Server": "0.0.0.1",
"User": "user@company.com",
"Pass": "123456789",
"Port": "25"
}





share|improve this answer



















  • 3




    Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line. ;)
    – James Wilkins
    Mar 13 '17 at 22:52












  • @James Wilkins: Very valid concerns. However, I actually prefer this notation over using it as extension method - this way I know what is being done where, and can copy-paste from 1 place to another, without getting problems because of missing import namespaces. The only problem is, MS uses namespaces for taxonomy instead of name collision prevention - because of that, the namespaces are too long. Also, if you remove the namspaces and use the extension methods, the same kind of people will start complaining about the code not compiling. Not everyone uses an IDE, so it's better this way.
    – Stefan Steiger
    Mar 14 '17 at 9:48












  • I find most people don't bother to put the "usings" in their code examples, which is a case for your point, but also why extension methods fail for the other point. ;)
    – James Wilkins
    Mar 14 '17 at 18:45










  • @James Wilkins: I completely agree. Usually because they have the using in their code, so they don't know it's an extension method, or because they don't know which of all the using clauses would be needed, so they just post without it. It's getting better with VS 2017, but VS2017 runs only on Windows, plus it's slow (IMHO) - which wouldn't be that bad if it didn't block input, or if starting a debbugger wouldn't take an eternity, but unfortunately, in VS it does.
    – Stefan Steiger
    Mar 15 '17 at 6:52








  • 1




    @JedatKinports: No, only injection. Even if you'd write a static method, you'd still need the configuration. You could just read a JSON/YAML file manually, though. But that will eliminate overwrites, such as usersecrets or others (e.g. configuration from registry).
    – Stefan Steiger
    Feb 21 at 8:19


















up vote
52
down vote













The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.



In Startup.cs



public void ConfigureServices(IServiceCollection services)
{
...
// Add the whole configuration object here.
services.AddSingleton<IConfiguration>(Configuration);
}


In your controller add a field for the configuration and a parameter for it on a constructor



private readonly IConfiguration configuration;

public HomeController(IConfiguration config)
{
configuration = config;
}


Now later in your view code you can access it like:



connectionString = configuration.GetConnectionString("DefaultConnection");





share|improve this answer





















  • Wouldn't do it like that. If you work without entity framework, you better register a connection factory as singleton, e.g. to use with dapper. You can then still expose a connectionString property if you need to, but I bet it wouldn't be necessary in 99% of cases.
    – Stefan Steiger
    Apr 3 at 6:37










  • But how to access Configuration in Models instead of Controller?
    – Tanmay
    Apr 6 at 13:45










  • @Tanmay: You create your Models in such a way that they expect Configuration in the constructor. Then when you create the model in the controller, you pass it Configuration in the constructor. If you call some class in the Controller, which then creates your models, then you need to pass this class the Configuration as well, either in the constructor, or as properties, or as an additional method argument.
    – Stefan Steiger
    Sep 12 at 13:02




















up vote
4
down vote













See link for more info:
https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings



JSON



    {
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
}


C# Startup.cs



public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}





share|improve this answer




























    up vote
    1
    down vote













    The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable



    public Startup(IHostingEnvironment env)
    {
    var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();
    _config = builder.Build();
    }


    And then I could set the configuration string as follows:



    var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 


    This is on dotnet core 1.1






    share|improve this answer

















    • 4




      how can i access _config in my control?
      – sunny
      Jun 5 '17 at 19:25










    • By adding it to the DI container in ConfigureServices in Startup.cs.
      – Stefan Steiger
      Feb 21 at 8:23


















    up vote
    0
    down vote













    You can use configuration extension method : getConnectionString ("DefaultConnection")



    https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/Extensions/Configuration/ConfigurationExtensions/index.html#Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString






    share|improve this answer

















    • 2




      The link appears to be dead
      – Mark Wagoner
      Sep 20 at 16:43










    protected by Yuval Itzchakov Feb 21 at 8:24



    Thank you for your interest in this question.
    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



    Would you like to answer one of these unanswered questions instead?














    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    44
    down vote



    accepted










    You can do this with the GetConnectionString extension-method:



    string conString = Microsoft
    .Extensions
    .Configuration
    .ConfigurationExtensions
    .GetConnectionString(this.Configuration, "DefaultConnection");

    System.Console.WriteLine(conString);


    or with a structured-class for DI:



    public class SmtpConfig
    {
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
    }


    Startup:



    public IConfigurationRoot Configuration { get; }


    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
    // http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
    // services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));


    And then in the home-controller:



    public class HomeController : Controller
    {

    public SmtpConfig SmtpConfig { get; }
    public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
    {
    SmtpConfig = smtpConfig.Value;
    } //Action Controller


    public IActionResult Index()
    {
    System.Console.WriteLine(SmtpConfig);
    return View();
    }


    with this in appsettings.json:



    "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
    },

    "Smtp": {
    "Server": "0.0.0.1",
    "User": "user@company.com",
    "Pass": "123456789",
    "Port": "25"
    }





    share|improve this answer



















    • 3




      Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line. ;)
      – James Wilkins
      Mar 13 '17 at 22:52












    • @James Wilkins: Very valid concerns. However, I actually prefer this notation over using it as extension method - this way I know what is being done where, and can copy-paste from 1 place to another, without getting problems because of missing import namespaces. The only problem is, MS uses namespaces for taxonomy instead of name collision prevention - because of that, the namespaces are too long. Also, if you remove the namspaces and use the extension methods, the same kind of people will start complaining about the code not compiling. Not everyone uses an IDE, so it's better this way.
      – Stefan Steiger
      Mar 14 '17 at 9:48












    • I find most people don't bother to put the "usings" in their code examples, which is a case for your point, but also why extension methods fail for the other point. ;)
      – James Wilkins
      Mar 14 '17 at 18:45










    • @James Wilkins: I completely agree. Usually because they have the using in their code, so they don't know it's an extension method, or because they don't know which of all the using clauses would be needed, so they just post without it. It's getting better with VS 2017, but VS2017 runs only on Windows, plus it's slow (IMHO) - which wouldn't be that bad if it didn't block input, or if starting a debbugger wouldn't take an eternity, but unfortunately, in VS it does.
      – Stefan Steiger
      Mar 15 '17 at 6:52








    • 1




      @JedatKinports: No, only injection. Even if you'd write a static method, you'd still need the configuration. You could just read a JSON/YAML file manually, though. But that will eliminate overwrites, such as usersecrets or others (e.g. configuration from registry).
      – Stefan Steiger
      Feb 21 at 8:19















    up vote
    44
    down vote



    accepted










    You can do this with the GetConnectionString extension-method:



    string conString = Microsoft
    .Extensions
    .Configuration
    .ConfigurationExtensions
    .GetConnectionString(this.Configuration, "DefaultConnection");

    System.Console.WriteLine(conString);


    or with a structured-class for DI:



    public class SmtpConfig
    {
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
    }


    Startup:



    public IConfigurationRoot Configuration { get; }


    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
    // http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
    // services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));


    And then in the home-controller:



    public class HomeController : Controller
    {

    public SmtpConfig SmtpConfig { get; }
    public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
    {
    SmtpConfig = smtpConfig.Value;
    } //Action Controller


    public IActionResult Index()
    {
    System.Console.WriteLine(SmtpConfig);
    return View();
    }


    with this in appsettings.json:



    "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
    },

    "Smtp": {
    "Server": "0.0.0.1",
    "User": "user@company.com",
    "Pass": "123456789",
    "Port": "25"
    }





    share|improve this answer



















    • 3




      Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line. ;)
      – James Wilkins
      Mar 13 '17 at 22:52












    • @James Wilkins: Very valid concerns. However, I actually prefer this notation over using it as extension method - this way I know what is being done where, and can copy-paste from 1 place to another, without getting problems because of missing import namespaces. The only problem is, MS uses namespaces for taxonomy instead of name collision prevention - because of that, the namespaces are too long. Also, if you remove the namspaces and use the extension methods, the same kind of people will start complaining about the code not compiling. Not everyone uses an IDE, so it's better this way.
      – Stefan Steiger
      Mar 14 '17 at 9:48












    • I find most people don't bother to put the "usings" in their code examples, which is a case for your point, but also why extension methods fail for the other point. ;)
      – James Wilkins
      Mar 14 '17 at 18:45










    • @James Wilkins: I completely agree. Usually because they have the using in their code, so they don't know it's an extension method, or because they don't know which of all the using clauses would be needed, so they just post without it. It's getting better with VS 2017, but VS2017 runs only on Windows, plus it's slow (IMHO) - which wouldn't be that bad if it didn't block input, or if starting a debbugger wouldn't take an eternity, but unfortunately, in VS it does.
      – Stefan Steiger
      Mar 15 '17 at 6:52








    • 1




      @JedatKinports: No, only injection. Even if you'd write a static method, you'd still need the configuration. You could just read a JSON/YAML file manually, though. But that will eliminate overwrites, such as usersecrets or others (e.g. configuration from registry).
      – Stefan Steiger
      Feb 21 at 8:19













    up vote
    44
    down vote



    accepted







    up vote
    44
    down vote



    accepted






    You can do this with the GetConnectionString extension-method:



    string conString = Microsoft
    .Extensions
    .Configuration
    .ConfigurationExtensions
    .GetConnectionString(this.Configuration, "DefaultConnection");

    System.Console.WriteLine(conString);


    or with a structured-class for DI:



    public class SmtpConfig
    {
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
    }


    Startup:



    public IConfigurationRoot Configuration { get; }


    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
    // http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
    // services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));


    And then in the home-controller:



    public class HomeController : Controller
    {

    public SmtpConfig SmtpConfig { get; }
    public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
    {
    SmtpConfig = smtpConfig.Value;
    } //Action Controller


    public IActionResult Index()
    {
    System.Console.WriteLine(SmtpConfig);
    return View();
    }


    with this in appsettings.json:



    "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
    },

    "Smtp": {
    "Server": "0.0.0.1",
    "User": "user@company.com",
    "Pass": "123456789",
    "Port": "25"
    }





    share|improve this answer














    You can do this with the GetConnectionString extension-method:



    string conString = Microsoft
    .Extensions
    .Configuration
    .ConfigurationExtensions
    .GetConnectionString(this.Configuration, "DefaultConnection");

    System.Console.WriteLine(conString);


    or with a structured-class for DI:



    public class SmtpConfig
    {
    public string Server { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public int Port { get; set; }
    }


    Startup:



    public IConfigurationRoot Configuration { get; }


    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
    // http://developer.telerik.com/featured/new-configuration-model-asp-net-core/
    // services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));
    Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<SmtpConfig>(services, Configuration.GetSection("Smtp"));


    And then in the home-controller:



    public class HomeController : Controller
    {

    public SmtpConfig SmtpConfig { get; }
    public HomeController(Microsoft.Extensions.Options.IOptions<SmtpConfig> smtpConfig)
    {
    SmtpConfig = smtpConfig.Value;
    } //Action Controller


    public IActionResult Index()
    {
    System.Console.WriteLine(SmtpConfig);
    return View();
    }


    with this in appsettings.json:



    "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
    },

    "Smtp": {
    "Server": "0.0.0.1",
    "User": "user@company.com",
    "Pass": "123456789",
    "Port": "25"
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 18 '17 at 9:26









    Aran Mulholland

    15.1k20117203




    15.1k20117203










    answered Nov 28 '16 at 12:27









    Stefan Steiger

    43.4k54263351




    43.4k54263351








    • 3




      Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line. ;)
      – James Wilkins
      Mar 13 '17 at 22:52












    • @James Wilkins: Very valid concerns. However, I actually prefer this notation over using it as extension method - this way I know what is being done where, and can copy-paste from 1 place to another, without getting problems because of missing import namespaces. The only problem is, MS uses namespaces for taxonomy instead of name collision prevention - because of that, the namespaces are too long. Also, if you remove the namspaces and use the extension methods, the same kind of people will start complaining about the code not compiling. Not everyone uses an IDE, so it's better this way.
      – Stefan Steiger
      Mar 14 '17 at 9:48












    • I find most people don't bother to put the "usings" in their code examples, which is a case for your point, but also why extension methods fail for the other point. ;)
      – James Wilkins
      Mar 14 '17 at 18:45










    • @James Wilkins: I completely agree. Usually because they have the using in their code, so they don't know it's an extension method, or because they don't know which of all the using clauses would be needed, so they just post without it. It's getting better with VS 2017, but VS2017 runs only on Windows, plus it's slow (IMHO) - which wouldn't be that bad if it didn't block input, or if starting a debbugger wouldn't take an eternity, but unfortunately, in VS it does.
      – Stefan Steiger
      Mar 15 '17 at 6:52








    • 1




      @JedatKinports: No, only injection. Even if you'd write a static method, you'd still need the configuration. You could just read a JSON/YAML file manually, though. But that will eliminate overwrites, such as usersecrets or others (e.g. configuration from registry).
      – Stefan Steiger
      Feb 21 at 8:19














    • 3




      Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line. ;)
      – James Wilkins
      Mar 13 '17 at 22:52












    • @James Wilkins: Very valid concerns. However, I actually prefer this notation over using it as extension method - this way I know what is being done where, and can copy-paste from 1 place to another, without getting problems because of missing import namespaces. The only problem is, MS uses namespaces for taxonomy instead of name collision prevention - because of that, the namespaces are too long. Also, if you remove the namspaces and use the extension methods, the same kind of people will start complaining about the code not compiling. Not everyone uses an IDE, so it's better this way.
      – Stefan Steiger
      Mar 14 '17 at 9:48












    • I find most people don't bother to put the "usings" in their code examples, which is a case for your point, but also why extension methods fail for the other point. ;)
      – James Wilkins
      Mar 14 '17 at 18:45










    • @James Wilkins: I completely agree. Usually because they have the using in their code, so they don't know it's an extension method, or because they don't know which of all the using clauses would be needed, so they just post without it. It's getting better with VS 2017, but VS2017 runs only on Windows, plus it's slow (IMHO) - which wouldn't be that bad if it didn't block input, or if starting a debbugger wouldn't take an eternity, but unfortunately, in VS it does.
      – Stefan Steiger
      Mar 15 '17 at 6:52








    • 1




      @JedatKinports: No, only injection. Even if you'd write a static method, you'd still need the configuration. You could just read a JSON/YAML file manually, though. But that will eliminate overwrites, such as usersecrets or others (e.g. configuration from registry).
      – Stefan Steiger
      Feb 21 at 8:19








    3




    3




    Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line. ;)
    – James Wilkins
    Mar 13 '17 at 22:52






    Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line. ;)
    – James Wilkins
    Mar 13 '17 at 22:52














    @James Wilkins: Very valid concerns. However, I actually prefer this notation over using it as extension method - this way I know what is being done where, and can copy-paste from 1 place to another, without getting problems because of missing import namespaces. The only problem is, MS uses namespaces for taxonomy instead of name collision prevention - because of that, the namespaces are too long. Also, if you remove the namspaces and use the extension methods, the same kind of people will start complaining about the code not compiling. Not everyone uses an IDE, so it's better this way.
    – Stefan Steiger
    Mar 14 '17 at 9:48






    @James Wilkins: Very valid concerns. However, I actually prefer this notation over using it as extension method - this way I know what is being done where, and can copy-paste from 1 place to another, without getting problems because of missing import namespaces. The only problem is, MS uses namespaces for taxonomy instead of name collision prevention - because of that, the namespaces are too long. Also, if you remove the namspaces and use the extension methods, the same kind of people will start complaining about the code not compiling. Not everyone uses an IDE, so it's better this way.
    – Stefan Steiger
    Mar 14 '17 at 9:48














    I find most people don't bother to put the "usings" in their code examples, which is a case for your point, but also why extension methods fail for the other point. ;)
    – James Wilkins
    Mar 14 '17 at 18:45




    I find most people don't bother to put the "usings" in their code examples, which is a case for your point, but also why extension methods fail for the other point. ;)
    – James Wilkins
    Mar 14 '17 at 18:45












    @James Wilkins: I completely agree. Usually because they have the using in their code, so they don't know it's an extension method, or because they don't know which of all the using clauses would be needed, so they just post without it. It's getting better with VS 2017, but VS2017 runs only on Windows, plus it's slow (IMHO) - which wouldn't be that bad if it didn't block input, or if starting a debbugger wouldn't take an eternity, but unfortunately, in VS it does.
    – Stefan Steiger
    Mar 15 '17 at 6:52






    @James Wilkins: I completely agree. Usually because they have the using in their code, so they don't know it's an extension method, or because they don't know which of all the using clauses would be needed, so they just post without it. It's getting better with VS 2017, but VS2017 runs only on Windows, plus it's slow (IMHO) - which wouldn't be that bad if it didn't block input, or if starting a debbugger wouldn't take an eternity, but unfortunately, in VS it does.
    – Stefan Steiger
    Mar 15 '17 at 6:52






    1




    1




    @JedatKinports: No, only injection. Even if you'd write a static method, you'd still need the configuration. You could just read a JSON/YAML file manually, though. But that will eliminate overwrites, such as usersecrets or others (e.g. configuration from registry).
    – Stefan Steiger
    Feb 21 at 8:19




    @JedatKinports: No, only injection. Even if you'd write a static method, you'd still need the configuration. You could just read a JSON/YAML file manually, though. But that will eliminate overwrites, such as usersecrets or others (e.g. configuration from registry).
    – Stefan Steiger
    Feb 21 at 8:19












    up vote
    52
    down vote













    The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.



    In Startup.cs



    public void ConfigureServices(IServiceCollection services)
    {
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
    }


    In your controller add a field for the configuration and a parameter for it on a constructor



    private readonly IConfiguration configuration;

    public HomeController(IConfiguration config)
    {
    configuration = config;
    }


    Now later in your view code you can access it like:



    connectionString = configuration.GetConnectionString("DefaultConnection");





    share|improve this answer





















    • Wouldn't do it like that. If you work without entity framework, you better register a connection factory as singleton, e.g. to use with dapper. You can then still expose a connectionString property if you need to, but I bet it wouldn't be necessary in 99% of cases.
      – Stefan Steiger
      Apr 3 at 6:37










    • But how to access Configuration in Models instead of Controller?
      – Tanmay
      Apr 6 at 13:45










    • @Tanmay: You create your Models in such a way that they expect Configuration in the constructor. Then when you create the model in the controller, you pass it Configuration in the constructor. If you call some class in the Controller, which then creates your models, then you need to pass this class the Configuration as well, either in the constructor, or as properties, or as an additional method argument.
      – Stefan Steiger
      Sep 12 at 13:02

















    up vote
    52
    down vote













    The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.



    In Startup.cs



    public void ConfigureServices(IServiceCollection services)
    {
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
    }


    In your controller add a field for the configuration and a parameter for it on a constructor



    private readonly IConfiguration configuration;

    public HomeController(IConfiguration config)
    {
    configuration = config;
    }


    Now later in your view code you can access it like:



    connectionString = configuration.GetConnectionString("DefaultConnection");





    share|improve this answer





















    • Wouldn't do it like that. If you work without entity framework, you better register a connection factory as singleton, e.g. to use with dapper. You can then still expose a connectionString property if you need to, but I bet it wouldn't be necessary in 99% of cases.
      – Stefan Steiger
      Apr 3 at 6:37










    • But how to access Configuration in Models instead of Controller?
      – Tanmay
      Apr 6 at 13:45










    • @Tanmay: You create your Models in such a way that they expect Configuration in the constructor. Then when you create the model in the controller, you pass it Configuration in the constructor. If you call some class in the Controller, which then creates your models, then you need to pass this class the Configuration as well, either in the constructor, or as properties, or as an additional method argument.
      – Stefan Steiger
      Sep 12 at 13:02















    up vote
    52
    down vote










    up vote
    52
    down vote









    The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.



    In Startup.cs



    public void ConfigureServices(IServiceCollection services)
    {
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
    }


    In your controller add a field for the configuration and a parameter for it on a constructor



    private readonly IConfiguration configuration;

    public HomeController(IConfiguration config)
    {
    configuration = config;
    }


    Now later in your view code you can access it like:



    connectionString = configuration.GetConnectionString("DefaultConnection");





    share|improve this answer












    The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.



    In Startup.cs



    public void ConfigureServices(IServiceCollection services)
    {
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
    }


    In your controller add a field for the configuration and a parameter for it on a constructor



    private readonly IConfiguration configuration;

    public HomeController(IConfiguration config)
    {
    configuration = config;
    }


    Now later in your view code you can access it like:



    connectionString = configuration.GetConnectionString("DefaultConnection");






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jul 14 '17 at 18:15









    Brad Patton

    1,26521834




    1,26521834












    • Wouldn't do it like that. If you work without entity framework, you better register a connection factory as singleton, e.g. to use with dapper. You can then still expose a connectionString property if you need to, but I bet it wouldn't be necessary in 99% of cases.
      – Stefan Steiger
      Apr 3 at 6:37










    • But how to access Configuration in Models instead of Controller?
      – Tanmay
      Apr 6 at 13:45










    • @Tanmay: You create your Models in such a way that they expect Configuration in the constructor. Then when you create the model in the controller, you pass it Configuration in the constructor. If you call some class in the Controller, which then creates your models, then you need to pass this class the Configuration as well, either in the constructor, or as properties, or as an additional method argument.
      – Stefan Steiger
      Sep 12 at 13:02




















    • Wouldn't do it like that. If you work without entity framework, you better register a connection factory as singleton, e.g. to use with dapper. You can then still expose a connectionString property if you need to, but I bet it wouldn't be necessary in 99% of cases.
      – Stefan Steiger
      Apr 3 at 6:37










    • But how to access Configuration in Models instead of Controller?
      – Tanmay
      Apr 6 at 13:45










    • @Tanmay: You create your Models in such a way that they expect Configuration in the constructor. Then when you create the model in the controller, you pass it Configuration in the constructor. If you call some class in the Controller, which then creates your models, then you need to pass this class the Configuration as well, either in the constructor, or as properties, or as an additional method argument.
      – Stefan Steiger
      Sep 12 at 13:02


















    Wouldn't do it like that. If you work without entity framework, you better register a connection factory as singleton, e.g. to use with dapper. You can then still expose a connectionString property if you need to, but I bet it wouldn't be necessary in 99% of cases.
    – Stefan Steiger
    Apr 3 at 6:37




    Wouldn't do it like that. If you work without entity framework, you better register a connection factory as singleton, e.g. to use with dapper. You can then still expose a connectionString property if you need to, but I bet it wouldn't be necessary in 99% of cases.
    – Stefan Steiger
    Apr 3 at 6:37












    But how to access Configuration in Models instead of Controller?
    – Tanmay
    Apr 6 at 13:45




    But how to access Configuration in Models instead of Controller?
    – Tanmay
    Apr 6 at 13:45












    @Tanmay: You create your Models in such a way that they expect Configuration in the constructor. Then when you create the model in the controller, you pass it Configuration in the constructor. If you call some class in the Controller, which then creates your models, then you need to pass this class the Configuration as well, either in the constructor, or as properties, or as an additional method argument.
    – Stefan Steiger
    Sep 12 at 13:02






    @Tanmay: You create your Models in such a way that they expect Configuration in the constructor. Then when you create the model in the controller, you pass it Configuration in the constructor. If you call some class in the Controller, which then creates your models, then you need to pass this class the Configuration as well, either in the constructor, or as properties, or as an additional method argument.
    – Stefan Steiger
    Sep 12 at 13:02












    up vote
    4
    down vote













    See link for more info:
    https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings



    JSON



        {
    "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
    },
    }


    C# Startup.cs



    public void ConfigureServices(IServiceCollection services)
    {
    services.AddDbContext<BloggingContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
    }





    share|improve this answer

























      up vote
      4
      down vote













      See link for more info:
      https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings



      JSON



          {
      "ConnectionStrings": {
      "BloggingDatabase": "Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
      },
      }


      C# Startup.cs



      public void ConfigureServices(IServiceCollection services)
      {
      services.AddDbContext<BloggingContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
      }





      share|improve this answer























        up vote
        4
        down vote










        up vote
        4
        down vote









        See link for more info:
        https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings



        JSON



            {
        "ConnectionStrings": {
        "BloggingDatabase": "Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
        },
        }


        C# Startup.cs



        public void ConfigureServices(IServiceCollection services)
        {
        services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
        }





        share|improve this answer












        See link for more info:
        https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings



        JSON



            {
        "ConnectionStrings": {
        "BloggingDatabase": "Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
        },
        }


        C# Startup.cs



        public void ConfigureServices(IServiceCollection services)
        {
        services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Sep 1 '17 at 0:19









        markokstate

        2882519




        2882519






















            up vote
            1
            down vote













            The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable



            public Startup(IHostingEnvironment env)
            {
            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
            _config = builder.Build();
            }


            And then I could set the configuration string as follows:



            var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 


            This is on dotnet core 1.1






            share|improve this answer

















            • 4




              how can i access _config in my control?
              – sunny
              Jun 5 '17 at 19:25










            • By adding it to the DI container in ConfigureServices in Startup.cs.
              – Stefan Steiger
              Feb 21 at 8:23















            up vote
            1
            down vote













            The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable



            public Startup(IHostingEnvironment env)
            {
            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
            _config = builder.Build();
            }


            And then I could set the configuration string as follows:



            var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 


            This is on dotnet core 1.1






            share|improve this answer

















            • 4




              how can i access _config in my control?
              – sunny
              Jun 5 '17 at 19:25










            • By adding it to the DI container in ConfigureServices in Startup.cs.
              – Stefan Steiger
              Feb 21 at 8:23













            up vote
            1
            down vote










            up vote
            1
            down vote









            The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable



            public Startup(IHostingEnvironment env)
            {
            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
            _config = builder.Build();
            }


            And then I could set the configuration string as follows:



            var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 


            This is on dotnet core 1.1






            share|improve this answer












            The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable



            public Startup(IHostingEnvironment env)
            {
            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
            _config = builder.Build();
            }


            And then I could set the configuration string as follows:



            var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 


            This is on dotnet core 1.1







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 28 '17 at 12:00









            Alex White

            9421020




            9421020








            • 4




              how can i access _config in my control?
              – sunny
              Jun 5 '17 at 19:25










            • By adding it to the DI container in ConfigureServices in Startup.cs.
              – Stefan Steiger
              Feb 21 at 8:23














            • 4




              how can i access _config in my control?
              – sunny
              Jun 5 '17 at 19:25










            • By adding it to the DI container in ConfigureServices in Startup.cs.
              – Stefan Steiger
              Feb 21 at 8:23








            4




            4




            how can i access _config in my control?
            – sunny
            Jun 5 '17 at 19:25




            how can i access _config in my control?
            – sunny
            Jun 5 '17 at 19:25












            By adding it to the DI container in ConfigureServices in Startup.cs.
            – Stefan Steiger
            Feb 21 at 8:23




            By adding it to the DI container in ConfigureServices in Startup.cs.
            – Stefan Steiger
            Feb 21 at 8:23










            up vote
            0
            down vote













            You can use configuration extension method : getConnectionString ("DefaultConnection")



            https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/Extensions/Configuration/ConfigurationExtensions/index.html#Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString






            share|improve this answer

















            • 2




              The link appears to be dead
              – Mark Wagoner
              Sep 20 at 16:43















            up vote
            0
            down vote













            You can use configuration extension method : getConnectionString ("DefaultConnection")



            https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/Extensions/Configuration/ConfigurationExtensions/index.html#Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString






            share|improve this answer

















            • 2




              The link appears to be dead
              – Mark Wagoner
              Sep 20 at 16:43













            up vote
            0
            down vote










            up vote
            0
            down vote









            You can use configuration extension method : getConnectionString ("DefaultConnection")



            https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/Extensions/Configuration/ConfigurationExtensions/index.html#Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString






            share|improve this answer












            You can use configuration extension method : getConnectionString ("DefaultConnection")



            https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/Extensions/Configuration/ConfigurationExtensions/index.html#Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 24 '16 at 14:10









            Ivano Scifoni

            113




            113








            • 2




              The link appears to be dead
              – Mark Wagoner
              Sep 20 at 16:43














            • 2




              The link appears to be dead
              – Mark Wagoner
              Sep 20 at 16:43








            2




            2




            The link appears to be dead
            – Mark Wagoner
            Sep 20 at 16:43




            The link appears to be dead
            – Mark Wagoner
            Sep 20 at 16:43





            protected by Yuval Itzchakov Feb 21 at 8:24



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?



            Popular posts from this blog

            Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

            Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

            A Topological Invariant for $pi_3(U(n))$