Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

asp.net core mvc - Read an app setting in my .Net 5 application without using DI

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: enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...