1

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.

Simone
  • 2,304
  • 6
  • 30
  • 79
  • Attributes must have their constructor parameters supplied where they're applied, therefore it does not support constructor dependencies provided from DI. – Fei Han Jan 26 '21 at 06:32
  • It's not what I meant. I have edited the question with another consideration. – Simone Jan 26 '21 at 20:59

0 Answers0