ASP.NET Core—access Configuration from static class
I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an easy way to access it. Is this possible?
namespace MyNamespace
{
public static class Config
{
public string Username => Configuration["Username"];
public string Password => Configuration["Password"];
}
}
Anywhere else in the app:
string username = Config.Username;
string password = Config.Password;
asp.net-core-mvc
add a comment |
I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an easy way to access it. Is this possible?
namespace MyNamespace
{
public static class Config
{
public string Username => Configuration["Username"];
public string Password => Configuration["Password"];
}
}
Anywhere else in the app:
string username = Config.Username;
string password = Config.Password;
asp.net-core-mvc
Consider using dependency inversion as apposed to service locator anti-pattern
– Nkosi
Aug 25 '17 at 16:20
By configuration you mean appsettings.json or app.config?
– bruno.almeida
Aug 25 '17 at 16:26
appsettings.json. Will update the question.
– birdus
Aug 25 '17 at 16:32
Using static class may be bad practice for unit testing: stackoverflow.com/a/38107134/2803565
– S.Serpooshan
Dec 1 '18 at 9:47
why a static class? you can directly inject configuration or create a singleton
– Neville Nazerane
Jan 7 at 19:11
add a comment |
I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an easy way to access it. Is this possible?
namespace MyNamespace
{
public static class Config
{
public string Username => Configuration["Username"];
public string Password => Configuration["Password"];
}
}
Anywhere else in the app:
string username = Config.Username;
string password = Config.Password;
asp.net-core-mvc
I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an easy way to access it. Is this possible?
namespace MyNamespace
{
public static class Config
{
public string Username => Configuration["Username"];
public string Password => Configuration["Password"];
}
}
Anywhere else in the app:
string username = Config.Username;
string password = Config.Password;
asp.net-core-mvc
asp.net-core-mvc
edited Feb 14 at 20:54
Chris Stillwell
6,56674756
6,56674756
asked Aug 25 '17 at 16:16
birdusbirdus
2,525124980
2,525124980
Consider using dependency inversion as apposed to service locator anti-pattern
– Nkosi
Aug 25 '17 at 16:20
By configuration you mean appsettings.json or app.config?
– bruno.almeida
Aug 25 '17 at 16:26
appsettings.json. Will update the question.
– birdus
Aug 25 '17 at 16:32
Using static class may be bad practice for unit testing: stackoverflow.com/a/38107134/2803565
– S.Serpooshan
Dec 1 '18 at 9:47
why a static class? you can directly inject configuration or create a singleton
– Neville Nazerane
Jan 7 at 19:11
add a comment |
Consider using dependency inversion as apposed to service locator anti-pattern
– Nkosi
Aug 25 '17 at 16:20
By configuration you mean appsettings.json or app.config?
– bruno.almeida
Aug 25 '17 at 16:26
appsettings.json. Will update the question.
– birdus
Aug 25 '17 at 16:32
Using static class may be bad practice for unit testing: stackoverflow.com/a/38107134/2803565
– S.Serpooshan
Dec 1 '18 at 9:47
why a static class? you can directly inject configuration or create a singleton
– Neville Nazerane
Jan 7 at 19:11
Consider using dependency inversion as apposed to service locator anti-pattern
– Nkosi
Aug 25 '17 at 16:20
Consider using dependency inversion as apposed to service locator anti-pattern
– Nkosi
Aug 25 '17 at 16:20
By configuration you mean appsettings.json or app.config?
– bruno.almeida
Aug 25 '17 at 16:26
By configuration you mean appsettings.json or app.config?
– bruno.almeida
Aug 25 '17 at 16:26
appsettings.json. Will update the question.
– birdus
Aug 25 '17 at 16:32
appsettings.json. Will update the question.
– birdus
Aug 25 '17 at 16:32
Using static class may be bad practice for unit testing: stackoverflow.com/a/38107134/2803565
– S.Serpooshan
Dec 1 '18 at 9:47
Using static class may be bad practice for unit testing: stackoverflow.com/a/38107134/2803565
– S.Serpooshan
Dec 1 '18 at 9:47
why a static class? you can directly inject configuration or create a singleton
– Neville Nazerane
Jan 7 at 19:11
why a static class? you can directly inject configuration or create a singleton
– Neville Nazerane
Jan 7 at 19:11
add a comment |
6 Answers
6
active
oldest
votes
I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:
public class Program
{
public static IConfigurationRoot Configuration { get; set; }
public static void Main(string args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
// Edit:
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<HelloWorldOptions>(_configuration.GetSection("HelloWorld"));
// And so on...
}
}
1
Yeah, but how do you access this instance ofConfiguration
from another internal static class without having to rebuild it each time?
– Serj Sagan
Aug 7 '18 at 4:43
Then you should use theOptions
pattern.
– Tubbe
Aug 22 '18 at 19:35
4
@Tubbe Could you provide an example on how that works then? From what I've read in that article you'd still need to provide the options in the constructor, which isn't possible in a static class.
– CGundlach
Nov 13 '18 at 15:36
So how this supposed to work in a static class?
– Souvik Ghosh
Mar 21 at 8:33
add a comment |
A slightly shorter version based on the same principle as above...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }
To use in another static class:
string connString = Startup.StaticConfig.GetConnectionString("DefaultConnection");
share this configuration values among different class libraries will be tricky. Imagine you have infrastructure crosscutting sharing config / settings among several projects?
– Junior M
Dec 31 '18 at 12:40
I am confused why this is not the accepted answer. Is there some risk to this? Looks simple and functional.
– Chaim Eliyah
Jan 18 at 8:06
2
Because it's an anti-pattern. You should be able to inject all of the things a thing needs so you can substitute them during testing. When it's a static property with aprivate setter
, how are you going to substitute that? You'll have to make itpublic
just for testing, which is not right.
– Serj Sagan
Feb 13 at 3:25
add a comment |
Try avoid using a static class and use DI
namespace MyNamespace {
public interface IConfig {
string Username { get; }
string Password { get; }
}
public class Config : IConfig {
public Config(IConfiguration configuration) {
_configuration = configuration;
}
readonly IConfiguration _configuration;
public string Username => _configuration["Username"];
public string Password => _configuration["Password"];
}
}
The setup DI in StartUp class
public class Startup {
public void ConfigureServices(IServiceCollection services) {
//...
services.AddTransient<IConfig, Config>();
...
}
}
And use it like so
public class TestUsage {
public TestUsage(IConfig config) {
_config = config;
}
readonly IConfig _config;
public string Username => _config.Username;
public string Password => _config.Password;
}
1
If you are migrating a NET Framework to NET Core, you must modify ALL classes that use application settings in order to inject configuration values (IOptions, IConfiguration or whatever). If you have a huge project, editing classes will take a lot of time and testing. :-O Would love to see an easier way without DI and modifying classes constructors
– Junior M
Dec 31 '18 at 12:38
1
Why is it so bad to have a static class? I know dictionary access is fast, but it irks me just a little to have to useif(configuration["enabled"] == "True")
orif(configuration.GetValue<int>("enabled"))
when I feel likeif(MyStaticClass.Enabled)
is faster and lighter for methods which are called many times a second.
– Dinerdo
Feb 8 at 1:36
add a comment |
This has already been said but I'm going to say it.
Static classes are not a best practice of Object Oriented Programming. I think for this reason, .Net Core provides us with a way to get values through Dependency Inject. This is what I've noticed from my research but I am also speculating a bit. As developers, we need to follow this paradigm shift in order to use .Net Core well.
The Options Pattern is a good alternative to the static config. In your case, it'll look like this:
appsettings.json
{
"Username": "MyUsername",
"Password": "Password1234"
}
SystemUser.cs
public class SystemUser
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
}
Startup.cs
services.Configure<SystemUser>(Configuration);
And to use the SystemUser class, we do the following.
TestController.cs
public class TestController : Controller
{
private readonly SystemUser systemUser;
public TestController(IOptionsMonitor<SystemUser> systemUserOptions)
{
this.systemUser = systemUserOptions.CurrentValue;
}
public void SomeMethod()
{
var username = this.systemUser.Username; // "MyUsername"
var password = this.systemUser.Password; // "Password1234"
}
}
Even though we are not using a static class, I think this is the best alternative that fits your needs. Otherwise, you might have to use a static property inside the Startup class which is a scary solution imo.
add a comment |
Consider using the instructions here for ASP.NET Core Configuration.
You can create a class to store your configuration settings and then access the values, something like this:
_config.UserName
In Startup - ConfigureServices:
services.Configure<Config>(Configuration.GetSections("General"));
Then just inject your object wherever you need as:
IOptions<Config> config
How are you going to inject the object in a static class?
– mavi
Aug 2 '18 at 18:05
You inject the config into an instance rather than using a static class. Nowhere did I recommend attempting to inject the config into a static.
– mcbowes
Aug 7 '18 at 2:34
3
This question is specifically about using it in astatic class
– Serj Sagan
Aug 7 '18 at 4:41
1
@SerjSagan Even though the question asks specifically about static classes, they may not understand that there was a paradigm shift from .NET to .NET Core. Because of this, a static class is not the optimal answer and therefor the options pattern should be a valid answer.
– christo8989
Feb 12 at 21:05
add a comment |
The IConfiguration is Injectable anywhere within the Project. But in the case of static class, the option I am using and maybe only approach...
var Configuration = new ConfigurationBuilder()
.AddUserSecrets<Startup>()
.Build();
And, you can add required section, such in this code block above, I added 'UserSecrets'.
You can't DI into a static, so this is the wrong answer.
– billb
Dec 12 '17 at 21:03
Hi billb, this is what I mentioned above. We cannot DI into static class, and this is why the code block above. Where no DI is occurring but allowing to access configuration, such as 'UserSecrets' in code block
– irejwanul
Dec 22 '17 at 6:46
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45885615%2fasp-net-core-access-configuration-from-static-class%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:
public class Program
{
public static IConfigurationRoot Configuration { get; set; }
public static void Main(string args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
// Edit:
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<HelloWorldOptions>(_configuration.GetSection("HelloWorld"));
// And so on...
}
}
1
Yeah, but how do you access this instance ofConfiguration
from another internal static class without having to rebuild it each time?
– Serj Sagan
Aug 7 '18 at 4:43
Then you should use theOptions
pattern.
– Tubbe
Aug 22 '18 at 19:35
4
@Tubbe Could you provide an example on how that works then? From what I've read in that article you'd still need to provide the options in the constructor, which isn't possible in a static class.
– CGundlach
Nov 13 '18 at 15:36
So how this supposed to work in a static class?
– Souvik Ghosh
Mar 21 at 8:33
add a comment |
I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:
public class Program
{
public static IConfigurationRoot Configuration { get; set; }
public static void Main(string args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
// Edit:
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<HelloWorldOptions>(_configuration.GetSection("HelloWorld"));
// And so on...
}
}
1
Yeah, but how do you access this instance ofConfiguration
from another internal static class without having to rebuild it each time?
– Serj Sagan
Aug 7 '18 at 4:43
Then you should use theOptions
pattern.
– Tubbe
Aug 22 '18 at 19:35
4
@Tubbe Could you provide an example on how that works then? From what I've read in that article you'd still need to provide the options in the constructor, which isn't possible in a static class.
– CGundlach
Nov 13 '18 at 15:36
So how this supposed to work in a static class?
– Souvik Ghosh
Mar 21 at 8:33
add a comment |
I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:
public class Program
{
public static IConfigurationRoot Configuration { get; set; }
public static void Main(string args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
// Edit:
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<HelloWorldOptions>(_configuration.GetSection("HelloWorld"));
// And so on...
}
}
I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:
public class Program
{
public static IConfigurationRoot Configuration { get; set; }
public static void Main(string args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
// Edit:
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<HelloWorldOptions>(_configuration.GetSection("HelloWorld"));
// And so on...
}
}
edited Feb 14 at 20:54
Chris Stillwell
6,56674756
6,56674756
answered Sep 5 '17 at 7:37
TubbeTubbe
853518
853518
1
Yeah, but how do you access this instance ofConfiguration
from another internal static class without having to rebuild it each time?
– Serj Sagan
Aug 7 '18 at 4:43
Then you should use theOptions
pattern.
– Tubbe
Aug 22 '18 at 19:35
4
@Tubbe Could you provide an example on how that works then? From what I've read in that article you'd still need to provide the options in the constructor, which isn't possible in a static class.
– CGundlach
Nov 13 '18 at 15:36
So how this supposed to work in a static class?
– Souvik Ghosh
Mar 21 at 8:33
add a comment |
1
Yeah, but how do you access this instance ofConfiguration
from another internal static class without having to rebuild it each time?
– Serj Sagan
Aug 7 '18 at 4:43
Then you should use theOptions
pattern.
– Tubbe
Aug 22 '18 at 19:35
4
@Tubbe Could you provide an example on how that works then? From what I've read in that article you'd still need to provide the options in the constructor, which isn't possible in a static class.
– CGundlach
Nov 13 '18 at 15:36
So how this supposed to work in a static class?
– Souvik Ghosh
Mar 21 at 8:33
1
1
Yeah, but how do you access this instance of
Configuration
from another internal static class without having to rebuild it each time?– Serj Sagan
Aug 7 '18 at 4:43
Yeah, but how do you access this instance of
Configuration
from another internal static class without having to rebuild it each time?– Serj Sagan
Aug 7 '18 at 4:43
Then you should use the
Options
pattern.– Tubbe
Aug 22 '18 at 19:35
Then you should use the
Options
pattern.– Tubbe
Aug 22 '18 at 19:35
4
4
@Tubbe Could you provide an example on how that works then? From what I've read in that article you'd still need to provide the options in the constructor, which isn't possible in a static class.
– CGundlach
Nov 13 '18 at 15:36
@Tubbe Could you provide an example on how that works then? From what I've read in that article you'd still need to provide the options in the constructor, which isn't possible in a static class.
– CGundlach
Nov 13 '18 at 15:36
So how this supposed to work in a static class?
– Souvik Ghosh
Mar 21 at 8:33
So how this supposed to work in a static class?
– Souvik Ghosh
Mar 21 at 8:33
add a comment |
A slightly shorter version based on the same principle as above...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }
To use in another static class:
string connString = Startup.StaticConfig.GetConnectionString("DefaultConnection");
share this configuration values among different class libraries will be tricky. Imagine you have infrastructure crosscutting sharing config / settings among several projects?
– Junior M
Dec 31 '18 at 12:40
I am confused why this is not the accepted answer. Is there some risk to this? Looks simple and functional.
– Chaim Eliyah
Jan 18 at 8:06
2
Because it's an anti-pattern. You should be able to inject all of the things a thing needs so you can substitute them during testing. When it's a static property with aprivate setter
, how are you going to substitute that? You'll have to make itpublic
just for testing, which is not right.
– Serj Sagan
Feb 13 at 3:25
add a comment |
A slightly shorter version based on the same principle as above...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }
To use in another static class:
string connString = Startup.StaticConfig.GetConnectionString("DefaultConnection");
share this configuration values among different class libraries will be tricky. Imagine you have infrastructure crosscutting sharing config / settings among several projects?
– Junior M
Dec 31 '18 at 12:40
I am confused why this is not the accepted answer. Is there some risk to this? Looks simple and functional.
– Chaim Eliyah
Jan 18 at 8:06
2
Because it's an anti-pattern. You should be able to inject all of the things a thing needs so you can substitute them during testing. When it's a static property with aprivate setter
, how are you going to substitute that? You'll have to make itpublic
just for testing, which is not right.
– Serj Sagan
Feb 13 at 3:25
add a comment |
A slightly shorter version based on the same principle as above...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }
To use in another static class:
string connString = Startup.StaticConfig.GetConnectionString("DefaultConnection");
A slightly shorter version based on the same principle as above...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }
To use in another static class:
string connString = Startup.StaticConfig.GetConnectionString("DefaultConnection");
edited Feb 14 at 20:54
Chris Stillwell
6,56674756
6,56674756
answered Nov 7 '18 at 0:11
DeanCDeanC
711
711
share this configuration values among different class libraries will be tricky. Imagine you have infrastructure crosscutting sharing config / settings among several projects?
– Junior M
Dec 31 '18 at 12:40
I am confused why this is not the accepted answer. Is there some risk to this? Looks simple and functional.
– Chaim Eliyah
Jan 18 at 8:06
2
Because it's an anti-pattern. You should be able to inject all of the things a thing needs so you can substitute them during testing. When it's a static property with aprivate setter
, how are you going to substitute that? You'll have to make itpublic
just for testing, which is not right.
– Serj Sagan
Feb 13 at 3:25
add a comment |
share this configuration values among different class libraries will be tricky. Imagine you have infrastructure crosscutting sharing config / settings among several projects?
– Junior M
Dec 31 '18 at 12:40
I am confused why this is not the accepted answer. Is there some risk to this? Looks simple and functional.
– Chaim Eliyah
Jan 18 at 8:06
2
Because it's an anti-pattern. You should be able to inject all of the things a thing needs so you can substitute them during testing. When it's a static property with aprivate setter
, how are you going to substitute that? You'll have to make itpublic
just for testing, which is not right.
– Serj Sagan
Feb 13 at 3:25
share this configuration values among different class libraries will be tricky. Imagine you have infrastructure crosscutting sharing config / settings among several projects?
– Junior M
Dec 31 '18 at 12:40
share this configuration values among different class libraries will be tricky. Imagine you have infrastructure crosscutting sharing config / settings among several projects?
– Junior M
Dec 31 '18 at 12:40
I am confused why this is not the accepted answer. Is there some risk to this? Looks simple and functional.
– Chaim Eliyah
Jan 18 at 8:06
I am confused why this is not the accepted answer. Is there some risk to this? Looks simple and functional.
– Chaim Eliyah
Jan 18 at 8:06
2
2
Because it's an anti-pattern. You should be able to inject all of the things a thing needs so you can substitute them during testing. When it's a static property with a
private setter
, how are you going to substitute that? You'll have to make it public
just for testing, which is not right.– Serj Sagan
Feb 13 at 3:25
Because it's an anti-pattern. You should be able to inject all of the things a thing needs so you can substitute them during testing. When it's a static property with a
private setter
, how are you going to substitute that? You'll have to make it public
just for testing, which is not right.– Serj Sagan
Feb 13 at 3:25
add a comment |
Try avoid using a static class and use DI
namespace MyNamespace {
public interface IConfig {
string Username { get; }
string Password { get; }
}
public class Config : IConfig {
public Config(IConfiguration configuration) {
_configuration = configuration;
}
readonly IConfiguration _configuration;
public string Username => _configuration["Username"];
public string Password => _configuration["Password"];
}
}
The setup DI in StartUp class
public class Startup {
public void ConfigureServices(IServiceCollection services) {
//...
services.AddTransient<IConfig, Config>();
...
}
}
And use it like so
public class TestUsage {
public TestUsage(IConfig config) {
_config = config;
}
readonly IConfig _config;
public string Username => _config.Username;
public string Password => _config.Password;
}
1
If you are migrating a NET Framework to NET Core, you must modify ALL classes that use application settings in order to inject configuration values (IOptions, IConfiguration or whatever). If you have a huge project, editing classes will take a lot of time and testing. :-O Would love to see an easier way without DI and modifying classes constructors
– Junior M
Dec 31 '18 at 12:38
1
Why is it so bad to have a static class? I know dictionary access is fast, but it irks me just a little to have to useif(configuration["enabled"] == "True")
orif(configuration.GetValue<int>("enabled"))
when I feel likeif(MyStaticClass.Enabled)
is faster and lighter for methods which are called many times a second.
– Dinerdo
Feb 8 at 1:36
add a comment |
Try avoid using a static class and use DI
namespace MyNamespace {
public interface IConfig {
string Username { get; }
string Password { get; }
}
public class Config : IConfig {
public Config(IConfiguration configuration) {
_configuration = configuration;
}
readonly IConfiguration _configuration;
public string Username => _configuration["Username"];
public string Password => _configuration["Password"];
}
}
The setup DI in StartUp class
public class Startup {
public void ConfigureServices(IServiceCollection services) {
//...
services.AddTransient<IConfig, Config>();
...
}
}
And use it like so
public class TestUsage {
public TestUsage(IConfig config) {
_config = config;
}
readonly IConfig _config;
public string Username => _config.Username;
public string Password => _config.Password;
}
1
If you are migrating a NET Framework to NET Core, you must modify ALL classes that use application settings in order to inject configuration values (IOptions, IConfiguration or whatever). If you have a huge project, editing classes will take a lot of time and testing. :-O Would love to see an easier way without DI and modifying classes constructors
– Junior M
Dec 31 '18 at 12:38
1
Why is it so bad to have a static class? I know dictionary access is fast, but it irks me just a little to have to useif(configuration["enabled"] == "True")
orif(configuration.GetValue<int>("enabled"))
when I feel likeif(MyStaticClass.Enabled)
is faster and lighter for methods which are called many times a second.
– Dinerdo
Feb 8 at 1:36
add a comment |
Try avoid using a static class and use DI
namespace MyNamespace {
public interface IConfig {
string Username { get; }
string Password { get; }
}
public class Config : IConfig {
public Config(IConfiguration configuration) {
_configuration = configuration;
}
readonly IConfiguration _configuration;
public string Username => _configuration["Username"];
public string Password => _configuration["Password"];
}
}
The setup DI in StartUp class
public class Startup {
public void ConfigureServices(IServiceCollection services) {
//...
services.AddTransient<IConfig, Config>();
...
}
}
And use it like so
public class TestUsage {
public TestUsage(IConfig config) {
_config = config;
}
readonly IConfig _config;
public string Username => _config.Username;
public string Password => _config.Password;
}
Try avoid using a static class and use DI
namespace MyNamespace {
public interface IConfig {
string Username { get; }
string Password { get; }
}
public class Config : IConfig {
public Config(IConfiguration configuration) {
_configuration = configuration;
}
readonly IConfiguration _configuration;
public string Username => _configuration["Username"];
public string Password => _configuration["Password"];
}
}
The setup DI in StartUp class
public class Startup {
public void ConfigureServices(IServiceCollection services) {
//...
services.AddTransient<IConfig, Config>();
...
}
}
And use it like so
public class TestUsage {
public TestUsage(IConfig config) {
_config = config;
}
readonly IConfig _config;
public string Username => _config.Username;
public string Password => _config.Password;
}
edited Feb 14 at 20:53
Chris Stillwell
6,56674756
6,56674756
answered Sep 12 '18 at 23:22
tb-mtgtb-mtg
765
765
1
If you are migrating a NET Framework to NET Core, you must modify ALL classes that use application settings in order to inject configuration values (IOptions, IConfiguration or whatever). If you have a huge project, editing classes will take a lot of time and testing. :-O Would love to see an easier way without DI and modifying classes constructors
– Junior M
Dec 31 '18 at 12:38
1
Why is it so bad to have a static class? I know dictionary access is fast, but it irks me just a little to have to useif(configuration["enabled"] == "True")
orif(configuration.GetValue<int>("enabled"))
when I feel likeif(MyStaticClass.Enabled)
is faster and lighter for methods which are called many times a second.
– Dinerdo
Feb 8 at 1:36
add a comment |
1
If you are migrating a NET Framework to NET Core, you must modify ALL classes that use application settings in order to inject configuration values (IOptions, IConfiguration or whatever). If you have a huge project, editing classes will take a lot of time and testing. :-O Would love to see an easier way without DI and modifying classes constructors
– Junior M
Dec 31 '18 at 12:38
1
Why is it so bad to have a static class? I know dictionary access is fast, but it irks me just a little to have to useif(configuration["enabled"] == "True")
orif(configuration.GetValue<int>("enabled"))
when I feel likeif(MyStaticClass.Enabled)
is faster and lighter for methods which are called many times a second.
– Dinerdo
Feb 8 at 1:36
1
1
If you are migrating a NET Framework to NET Core, you must modify ALL classes that use application settings in order to inject configuration values (IOptions, IConfiguration or whatever). If you have a huge project, editing classes will take a lot of time and testing. :-O Would love to see an easier way without DI and modifying classes constructors
– Junior M
Dec 31 '18 at 12:38
If you are migrating a NET Framework to NET Core, you must modify ALL classes that use application settings in order to inject configuration values (IOptions, IConfiguration or whatever). If you have a huge project, editing classes will take a lot of time and testing. :-O Would love to see an easier way without DI and modifying classes constructors
– Junior M
Dec 31 '18 at 12:38
1
1
Why is it so bad to have a static class? I know dictionary access is fast, but it irks me just a little to have to use
if(configuration["enabled"] == "True")
or if(configuration.GetValue<int>("enabled"))
when I feel like if(MyStaticClass.Enabled)
is faster and lighter for methods which are called many times a second.– Dinerdo
Feb 8 at 1:36
Why is it so bad to have a static class? I know dictionary access is fast, but it irks me just a little to have to use
if(configuration["enabled"] == "True")
or if(configuration.GetValue<int>("enabled"))
when I feel like if(MyStaticClass.Enabled)
is faster and lighter for methods which are called many times a second.– Dinerdo
Feb 8 at 1:36
add a comment |
This has already been said but I'm going to say it.
Static classes are not a best practice of Object Oriented Programming. I think for this reason, .Net Core provides us with a way to get values through Dependency Inject. This is what I've noticed from my research but I am also speculating a bit. As developers, we need to follow this paradigm shift in order to use .Net Core well.
The Options Pattern is a good alternative to the static config. In your case, it'll look like this:
appsettings.json
{
"Username": "MyUsername",
"Password": "Password1234"
}
SystemUser.cs
public class SystemUser
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
}
Startup.cs
services.Configure<SystemUser>(Configuration);
And to use the SystemUser class, we do the following.
TestController.cs
public class TestController : Controller
{
private readonly SystemUser systemUser;
public TestController(IOptionsMonitor<SystemUser> systemUserOptions)
{
this.systemUser = systemUserOptions.CurrentValue;
}
public void SomeMethod()
{
var username = this.systemUser.Username; // "MyUsername"
var password = this.systemUser.Password; // "Password1234"
}
}
Even though we are not using a static class, I think this is the best alternative that fits your needs. Otherwise, you might have to use a static property inside the Startup class which is a scary solution imo.
add a comment |
This has already been said but I'm going to say it.
Static classes are not a best practice of Object Oriented Programming. I think for this reason, .Net Core provides us with a way to get values through Dependency Inject. This is what I've noticed from my research but I am also speculating a bit. As developers, we need to follow this paradigm shift in order to use .Net Core well.
The Options Pattern is a good alternative to the static config. In your case, it'll look like this:
appsettings.json
{
"Username": "MyUsername",
"Password": "Password1234"
}
SystemUser.cs
public class SystemUser
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
}
Startup.cs
services.Configure<SystemUser>(Configuration);
And to use the SystemUser class, we do the following.
TestController.cs
public class TestController : Controller
{
private readonly SystemUser systemUser;
public TestController(IOptionsMonitor<SystemUser> systemUserOptions)
{
this.systemUser = systemUserOptions.CurrentValue;
}
public void SomeMethod()
{
var username = this.systemUser.Username; // "MyUsername"
var password = this.systemUser.Password; // "Password1234"
}
}
Even though we are not using a static class, I think this is the best alternative that fits your needs. Otherwise, you might have to use a static property inside the Startup class which is a scary solution imo.
add a comment |
This has already been said but I'm going to say it.
Static classes are not a best practice of Object Oriented Programming. I think for this reason, .Net Core provides us with a way to get values through Dependency Inject. This is what I've noticed from my research but I am also speculating a bit. As developers, we need to follow this paradigm shift in order to use .Net Core well.
The Options Pattern is a good alternative to the static config. In your case, it'll look like this:
appsettings.json
{
"Username": "MyUsername",
"Password": "Password1234"
}
SystemUser.cs
public class SystemUser
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
}
Startup.cs
services.Configure<SystemUser>(Configuration);
And to use the SystemUser class, we do the following.
TestController.cs
public class TestController : Controller
{
private readonly SystemUser systemUser;
public TestController(IOptionsMonitor<SystemUser> systemUserOptions)
{
this.systemUser = systemUserOptions.CurrentValue;
}
public void SomeMethod()
{
var username = this.systemUser.Username; // "MyUsername"
var password = this.systemUser.Password; // "Password1234"
}
}
Even though we are not using a static class, I think this is the best alternative that fits your needs. Otherwise, you might have to use a static property inside the Startup class which is a scary solution imo.
This has already been said but I'm going to say it.
Static classes are not a best practice of Object Oriented Programming. I think for this reason, .Net Core provides us with a way to get values through Dependency Inject. This is what I've noticed from my research but I am also speculating a bit. As developers, we need to follow this paradigm shift in order to use .Net Core well.
The Options Pattern is a good alternative to the static config. In your case, it'll look like this:
appsettings.json
{
"Username": "MyUsername",
"Password": "Password1234"
}
SystemUser.cs
public class SystemUser
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
}
Startup.cs
services.Configure<SystemUser>(Configuration);
And to use the SystemUser class, we do the following.
TestController.cs
public class TestController : Controller
{
private readonly SystemUser systemUser;
public TestController(IOptionsMonitor<SystemUser> systemUserOptions)
{
this.systemUser = systemUserOptions.CurrentValue;
}
public void SomeMethod()
{
var username = this.systemUser.Username; // "MyUsername"
var password = this.systemUser.Password; // "Password1234"
}
}
Even though we are not using a static class, I think this is the best alternative that fits your needs. Otherwise, you might have to use a static property inside the Startup class which is a scary solution imo.
edited Feb 14 at 20:56
Chris Stillwell
6,56674756
6,56674756
answered Jan 7 at 19:08
christo8989christo8989
2,53221830
2,53221830
add a comment |
add a comment |
Consider using the instructions here for ASP.NET Core Configuration.
You can create a class to store your configuration settings and then access the values, something like this:
_config.UserName
In Startup - ConfigureServices:
services.Configure<Config>(Configuration.GetSections("General"));
Then just inject your object wherever you need as:
IOptions<Config> config
How are you going to inject the object in a static class?
– mavi
Aug 2 '18 at 18:05
You inject the config into an instance rather than using a static class. Nowhere did I recommend attempting to inject the config into a static.
– mcbowes
Aug 7 '18 at 2:34
3
This question is specifically about using it in astatic class
– Serj Sagan
Aug 7 '18 at 4:41
1
@SerjSagan Even though the question asks specifically about static classes, they may not understand that there was a paradigm shift from .NET to .NET Core. Because of this, a static class is not the optimal answer and therefor the options pattern should be a valid answer.
– christo8989
Feb 12 at 21:05
add a comment |
Consider using the instructions here for ASP.NET Core Configuration.
You can create a class to store your configuration settings and then access the values, something like this:
_config.UserName
In Startup - ConfigureServices:
services.Configure<Config>(Configuration.GetSections("General"));
Then just inject your object wherever you need as:
IOptions<Config> config
How are you going to inject the object in a static class?
– mavi
Aug 2 '18 at 18:05
You inject the config into an instance rather than using a static class. Nowhere did I recommend attempting to inject the config into a static.
– mcbowes
Aug 7 '18 at 2:34
3
This question is specifically about using it in astatic class
– Serj Sagan
Aug 7 '18 at 4:41
1
@SerjSagan Even though the question asks specifically about static classes, they may not understand that there was a paradigm shift from .NET to .NET Core. Because of this, a static class is not the optimal answer and therefor the options pattern should be a valid answer.
– christo8989
Feb 12 at 21:05
add a comment |
Consider using the instructions here for ASP.NET Core Configuration.
You can create a class to store your configuration settings and then access the values, something like this:
_config.UserName
In Startup - ConfigureServices:
services.Configure<Config>(Configuration.GetSections("General"));
Then just inject your object wherever you need as:
IOptions<Config> config
Consider using the instructions here for ASP.NET Core Configuration.
You can create a class to store your configuration settings and then access the values, something like this:
_config.UserName
In Startup - ConfigureServices:
services.Configure<Config>(Configuration.GetSections("General"));
Then just inject your object wherever you need as:
IOptions<Config> config
answered Aug 25 '17 at 20:20
mcbowesmcbowes
6351610
6351610
How are you going to inject the object in a static class?
– mavi
Aug 2 '18 at 18:05
You inject the config into an instance rather than using a static class. Nowhere did I recommend attempting to inject the config into a static.
– mcbowes
Aug 7 '18 at 2:34
3
This question is specifically about using it in astatic class
– Serj Sagan
Aug 7 '18 at 4:41
1
@SerjSagan Even though the question asks specifically about static classes, they may not understand that there was a paradigm shift from .NET to .NET Core. Because of this, a static class is not the optimal answer and therefor the options pattern should be a valid answer.
– christo8989
Feb 12 at 21:05
add a comment |
How are you going to inject the object in a static class?
– mavi
Aug 2 '18 at 18:05
You inject the config into an instance rather than using a static class. Nowhere did I recommend attempting to inject the config into a static.
– mcbowes
Aug 7 '18 at 2:34
3
This question is specifically about using it in astatic class
– Serj Sagan
Aug 7 '18 at 4:41
1
@SerjSagan Even though the question asks specifically about static classes, they may not understand that there was a paradigm shift from .NET to .NET Core. Because of this, a static class is not the optimal answer and therefor the options pattern should be a valid answer.
– christo8989
Feb 12 at 21:05
How are you going to inject the object in a static class?
– mavi
Aug 2 '18 at 18:05
How are you going to inject the object in a static class?
– mavi
Aug 2 '18 at 18:05
You inject the config into an instance rather than using a static class. Nowhere did I recommend attempting to inject the config into a static.
– mcbowes
Aug 7 '18 at 2:34
You inject the config into an instance rather than using a static class. Nowhere did I recommend attempting to inject the config into a static.
– mcbowes
Aug 7 '18 at 2:34
3
3
This question is specifically about using it in a
static class
– Serj Sagan
Aug 7 '18 at 4:41
This question is specifically about using it in a
static class
– Serj Sagan
Aug 7 '18 at 4:41
1
1
@SerjSagan Even though the question asks specifically about static classes, they may not understand that there was a paradigm shift from .NET to .NET Core. Because of this, a static class is not the optimal answer and therefor the options pattern should be a valid answer.
– christo8989
Feb 12 at 21:05
@SerjSagan Even though the question asks specifically about static classes, they may not understand that there was a paradigm shift from .NET to .NET Core. Because of this, a static class is not the optimal answer and therefor the options pattern should be a valid answer.
– christo8989
Feb 12 at 21:05
add a comment |
The IConfiguration is Injectable anywhere within the Project. But in the case of static class, the option I am using and maybe only approach...
var Configuration = new ConfigurationBuilder()
.AddUserSecrets<Startup>()
.Build();
And, you can add required section, such in this code block above, I added 'UserSecrets'.
You can't DI into a static, so this is the wrong answer.
– billb
Dec 12 '17 at 21:03
Hi billb, this is what I mentioned above. We cannot DI into static class, and this is why the code block above. Where no DI is occurring but allowing to access configuration, such as 'UserSecrets' in code block
– irejwanul
Dec 22 '17 at 6:46
add a comment |
The IConfiguration is Injectable anywhere within the Project. But in the case of static class, the option I am using and maybe only approach...
var Configuration = new ConfigurationBuilder()
.AddUserSecrets<Startup>()
.Build();
And, you can add required section, such in this code block above, I added 'UserSecrets'.
You can't DI into a static, so this is the wrong answer.
– billb
Dec 12 '17 at 21:03
Hi billb, this is what I mentioned above. We cannot DI into static class, and this is why the code block above. Where no DI is occurring but allowing to access configuration, such as 'UserSecrets' in code block
– irejwanul
Dec 22 '17 at 6:46
add a comment |
The IConfiguration is Injectable anywhere within the Project. But in the case of static class, the option I am using and maybe only approach...
var Configuration = new ConfigurationBuilder()
.AddUserSecrets<Startup>()
.Build();
And, you can add required section, such in this code block above, I added 'UserSecrets'.
The IConfiguration is Injectable anywhere within the Project. But in the case of static class, the option I am using and maybe only approach...
var Configuration = new ConfigurationBuilder()
.AddUserSecrets<Startup>()
.Build();
And, you can add required section, such in this code block above, I added 'UserSecrets'.
answered Sep 15 '17 at 6:23
irejwanulirejwanul
94
94
You can't DI into a static, so this is the wrong answer.
– billb
Dec 12 '17 at 21:03
Hi billb, this is what I mentioned above. We cannot DI into static class, and this is why the code block above. Where no DI is occurring but allowing to access configuration, such as 'UserSecrets' in code block
– irejwanul
Dec 22 '17 at 6:46
add a comment |
You can't DI into a static, so this is the wrong answer.
– billb
Dec 12 '17 at 21:03
Hi billb, this is what I mentioned above. We cannot DI into static class, and this is why the code block above. Where no DI is occurring but allowing to access configuration, such as 'UserSecrets' in code block
– irejwanul
Dec 22 '17 at 6:46
You can't DI into a static, so this is the wrong answer.
– billb
Dec 12 '17 at 21:03
You can't DI into a static, so this is the wrong answer.
– billb
Dec 12 '17 at 21:03
Hi billb, this is what I mentioned above. We cannot DI into static class, and this is why the code block above. Where no DI is occurring but allowing to access configuration, such as 'UserSecrets' in code block
– irejwanul
Dec 22 '17 at 6:46
Hi billb, this is what I mentioned above. We cannot DI into static class, and this is why the code block above. Where no DI is occurring but allowing to access configuration, such as 'UserSecrets' in code block
– irejwanul
Dec 22 '17 at 6:46
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45885615%2fasp-net-core-access-configuration-from-static-class%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Consider using dependency inversion as apposed to service locator anti-pattern
– Nkosi
Aug 25 '17 at 16:20
By configuration you mean appsettings.json or app.config?
– bruno.almeida
Aug 25 '17 at 16:26
appsettings.json. Will update the question.
– birdus
Aug 25 '17 at 16:32
Using static class may be bad practice for unit testing: stackoverflow.com/a/38107134/2803565
– S.Serpooshan
Dec 1 '18 at 9:47
why a static class? you can directly inject configuration or create a singleton
– Neville Nazerane
Jan 7 at 19:11