I created an MVC application using .Net 5.
Then I created a custom Attribute should read some settings from appsettings.json
.
Here a working solution:
public class MyCustomAttribute : Attribute
{
public MyCustomAttribute(string key)
: base()
{
IConfiguration conf = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
var value = conf.GetValue<string>(key);
...
}
...
}
It works, but I do not think it is the correct solution. I try to explain why.
In the Program.cs
, beforse the host is builded, the startup
class is instantiated:
var builder = Host.CreateDefaultBuilder(args); builder
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
If I inject the IConfiguration
to the stratup, I can get the appsettings.json
values:
I think that from now, I have the appsettings.json and conseguently the configuration in memory.
So it seems really strange to me that in my custom attribute I must read the setting from the file again!
The question is: How can I read the in-memory configuration inside my custom attribute?
Is my consideration correct?
Thank you.
EDIT
I have found another solution, but I still does not like it:
I have modified the startup.cs
ctor in this way:
public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
this._environment = environment;
this._configuration = configuration;
AppDomain.CurrentDomain.SetData("conf", this._configuration);
}
And the ctor of MyCustomAttribute
in this way:
public class MyCustomAttribute : Attribute
{
public MyCustomAttribute(string key)
: base()
{
var conf = AppDomain.CurrentDomain.GetData("conf") as IConfiguration;
var value = conf.GetValue<string>(key);
...
}
...
}
Also this solution works. But I hope something out-of-the-box in .Net 5 exists. I would expect the normal behavior when the configuration is read, would be something similar to my solution.
question from:
https://stackoverflow.com/questions/65875780/read-an-app-setting-in-my-net-5-application-without-using-di 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…